gpt4 book ai didi

Java(初学者): Displaying the first name alphabetically and last name alphabetically after being given a list of names from the user

转载 作者:行者123 更新时间:2023-12-01 18:02:03 33 4
gpt4 key购买 nike

我一直在解决一个问题:

"Design a program that asks the user for a series of names (in no particular order). After the final person’s name has been entered, the program should display the name that is first alphabetically and the name that is last alphabetically.

For example, if the user enters the names Kristin, Joel, Adam, Beth, Zeb, and Chris, the program would display Adam and Zeb."

我有一个名为 getString 的函数,它返回一个有效的字符串输入;还有一个名为 displayResults 的模块,它按字母顺序显示名字,按字母顺序显示姓氏。我还使用“q”作为退出 while 循环的哨兵值。

但是,我遇到了一个问题,如果我输入“bob”、“david”、“alex”和“charlie”等名称,它会将名字正确显示为“alex”,但是将错误地将姓氏显示为“charlie”而不是“david”。我尝试检查我的代码是否有错误,但无法找到出错的地方。如有任何帮助,我们将不胜感激。

name = getString("Please enter a name, or input q to exit.");

if(!name.equals("q")) {
low = name;
high = name;
}

while(!name.equals("q")) {
int x;
x = name.compareToIgnoreCase(low);
if(x == -1){
low = name;
}
x = name.compareToIgnoreCase(high);
if(x == 1) {
high = name;
}
name = getString("Please enter another name, or input q to exit.");
}

displayResults(low, high);

最佳答案

Java API documentation仅声明compareToIgnoreCase()“返回:负整数、零或正整数”。由于您分别将 x 与 1 和 -1 进行比较,因此您可能实际上收到了另一个返回值,因此未检测到真正的“高”。

另一种可能性是您的输入中可能存在不可见字符(例如空格或回车)。当我在我的机器上运行“david”.compareToIgnoreCase(“charlie”)时,它返回-67。

关于Java(初学者): Displaying the first name alphabetically and last name alphabetically after being given a list of names from the user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40167883/

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