java - 如果 lastName 的第一个字符在 A 和 M 之间,我如何返回 1,如果 N 到 Z,我如何返回 2?
问题描述
如果 lastName 的第一个字符在 A 和 M 之间,我需要修复 getLineNumberFor 方法以返回 1,否则如果它在 N 和 Z 之间,则返回 2。
在我的脑海中听起来很容易,但我不确定我应该在这里使用什么。不确定我是否应该使用 charAt。
import java.util.Scanner;
public class ConferenceRegistration {
/**
* Assists in guiding people to the proper line based on their last name.
*
* @param lastName The person's last name
* @return The line number based on the first letter of lastName
*/
public int getLineNumberFor(String lastName) {
int lineNumberOne = 1;
int lineNumberTwo = 2;
Scanner scanner = new Scanner(System.in);
lastName = scanner.nextLine();
char guess = lastName.charAt(0);
if(lastName >= 'm'){
return lineNumberOne;
}
else{
return lineNumberTwo;
}
/*
lineNumber should be set based on the first character of the person's last name
Line 1 - A thru M
Line 2 - N thru Z
*/
}
}
解决方案
尝试
if(guess <= 'm'){
这将让您只比较 中的第一个char
,String
因为>
和<
比较在char
s 上工作正常(因为它们基本上可以像 一样比较int
),但对于String
.
请注意,它<=不是>=
因为 Java char
a < b < z
。有关详细信息,请参阅ASCII 表。此外,如果您不希望用户输入“?”,则需要添加更多逻辑。得到 1,或“-”得到 2。
推荐阅读
- c# - 如何修复“每个表只能配置一列'Identity'。在Ef Core和Oracle中调用'ValueGeneratedNever'......
- laravel - Laravel:如何使用模型运行之外的数据创建 groupBy 并使用 where claus
- python - 根据 lambda 函数将 NumPy 整数列表值映射到列表
- vue.js - 无法即时更改过渡组的过渡
- java - 将密钥标识符作为 X509SubjectKeyIdentifier 签名失败的 SOAP XML WS-Security
- django - Django 使用略有不同的模板发送邮件
- encoding - 用于编码“UTF8”的无效字节序列:当我尝试使用 FormData 对象向服务器发布和图像时出现 0x00 响应
- c# - 命名空间“Microsoft”中不存在类型或命名空间名称“AspNetCore”(您是否缺少程序集引用?)
- python - 输入一次而不是多次询问
- build - 编译 grpc 错误 zlib_compress 和 zlib_decompress