gpt4 book ai didi

java - 如果姓氏的第一个字符在 A 和 M 之间,如何返回 1;如果姓氏的第一个字符在 N 到 Z 之间,如何返回 2?

转载 作者:行者123 更新时间:2023-11-30 01:52:59 26 4
gpt4 key购买 nike

我需要修复 getLineNumberFor 方法,以便如果 lastName 的第一个字符位于 A 和 M 之间,则返回 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

*/

}
}

最佳答案

您必须使用 chatAt(index) 来获取您要检查的字符,然后根据您的条件,您可以使用如下三元运算:

public int getLineNumberFor(String lastName) {
char c = lastName.charAt(0);
return c >= 'A' && c <= 'M' ? 1 : c >= 'N' && c <= 'Z' ? 2 : 0;
}

请注意,如果没有大小写正确,它将返回 0,您可以将其更改为任何默认值。

<小时/>

或者正如 @Pshemo 在评论中提到的,使用 il else 更具可读性,因此您可以将代码更改为:

public int getLineNumberFor(String lastName) {
char c = lastName.charAt(0);
if (c >= 'A' && c <= 'M') {
return 1;
} else if (c >= 'N' && c <= 'Z') {
return 2;
}
return 0;
}

关于java - 如果姓氏的第一个字符在 A 和 M 之间,如何返回 1;如果姓氏的第一个字符在 N 到 Z 之间,如何返回 2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55426263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com