gpt4 book ai didi

java - equalsIgnoreCase 方法不适用于 JOptionPane(或 Scanner)输入

转载 作者:太空宇宙 更新时间:2023-11-04 11:24:02 25 4
gpt4 key购买 nike

    // ask user to enter name of state capital
String answer = JOptionPane.showInputDialog("What is the capital of " +
question + "?");

// verify name of state capital is in citiesarray
boolean isPresent = false; int stateNum = 0;
System.out.println(answer); // troubleshooting line
for (int i = 0; i <= 49; i++) {
String city = citiesarray[i];
isPresent = answer.equalsIgnoreCase(city);
System.out.println(city); // troubleshooting line
System.out.println(answer.compareTo(city)); // troubleshooting line
System.out.println(isPresent); // troubleshooting line
if (isPresent == true) {
stateNum = i; break;
}
}
if (isPresent == false) {
JOptionPane.showMessageDialog(null, "That is incorrect. Please try another round.");
return;
}

每当我运行此代码时,无论我输入什么大写字母,我都会在循环的每次迭代中得到所有错误的 boolean 值。似乎对于 equalsIgnoreCase 返回 true 的任何城市的 compareTo 输出始终为 -1,但我不知道如何使用它来识别和解决我的问题。

我尝试了几种不同的方法,发现使用 Scanner 时,只要答案不包含空格,它似乎就可以工作,但这对于 JOptionPane 来说似乎并不重要,而且无论如何,无论州首府在哪里,我都需要它工作。

最佳答案

发布的代码工作正常,在调整循环限制后,我只需添加两行并将上面的代码复制到主方法中:

public static void main(String[] args) {
String[] citiesarray = { "New York", "Paris", "Berlin", "Brasilia" }; // not real ones, but wanted one with space
String question = "somewhere";

// ask user to enter name of state capital
String answer = JOptionPane.showInputDialog("What is the capital of " +
question + "?");

// verify name of state capital is in citiesarray
boolean isPresent = false; int stateNum = 0;
System.out.println(answer); // troubleshooting line
for (int i = 0; i < citiesarray.length; i++) {
String city = citiesarray[i];
isPresent = answer.equalsIgnoreCase(city);
System.out.println(city); // troubleshooting line
System.out.println(answer.compareTo(city)); // troubleshooting line
System.out.println(isPresent); // troubleshooting line
if (isPresent == true) {
stateNum = i; break;
}
}
if (isPresent == false) {
JOptionPane.showMessageDialog(null, "That is incorrect. Please try another round.");
return;
}
}

问题一定出在其他地方,可能是 citiesarray 的声明/初始化方式。

关于java - equalsIgnoreCase 方法不适用于 JOptionPane(或 Scanner)输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44566796/

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