2017-06-15 49 views
1
// 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,但我不知道如何使用它來識別和解決我的問題。equalsIgnoreCase方法不具有的JOptionPane(或掃描儀)輸入

我試過了幾個不同的東西,發現用Scanner,它似乎工作,只要答案沒有包含空格,但這似乎並不重要JOptionPane,無論如何,我需要無論國家的首都是什麼,這都是工作的。

+0

'citiesarray'中的值是什麼?另外,我會將SOP行更改爲'System.out.println(''「+ city +」'「);'來檢查錯誤的空間。 –

+0

首先,您驗證答案的方式不正確。 neverthless你在'citiesarray'中的值是什麼,你輸入到InputDialog的值是多少? – Jobin

+0

citiesarray中的值是從* .txt文件讀取的五十個州首府。 由於我不明白的原因,更改SOP行只打印第二個撇號。 在我缺少的數組值中可能存在某種轉義字符?那是一件事嗎? – Lucky

回答

0

張貼的代碼工作完美,我只是增加了兩行,上面的代碼複製到主方法,適應循環的限制後:

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正在申報/初始化。

+0

謝謝! 我不知道如何調整代碼的文件讀取部分來修復那裏發生的任何事情,但Freak的建議使用修剪在比較字符串的水平工作! – Lucky