equalsIgnoreCase方法不能与JOptionPane(或Scanner)输入一起使用

时间:2017-06-15 11:51:28

标签: java string java.util.scanner equals joptionpane

    // 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;
    }

每当我运行这段代码时,无论我输入什么资本,我都会在循环的每次迭代中得到所有假布尔值。对于任何应该为compareTo返回true的城市,equalsIgnoreCase输出似乎总是-1,但我不知道如何使用它来识别和解决我的问题。

我尝试了几件不同的事情,发现使用Scanner,只要答案没有包含空格,它似乎就可以工作,但这似乎与{{{{{{{{{ 1}},无论如何,无论国家的资本是什么,我都需要这个。

1 个答案:

答案 0 :(得分:0)

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

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被声明/初始化的方式。