2017-06-15 3 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; 
    } 

このコードを実行するたびに、入力した大文字とは無関係にループの繰り返しごとにすべての不正ブール値が返されます。 equalsIgnoreCaseが常に-1となる都市を出力する場合はcompareToのように見えますが、それを識別して問題を解決する方法はわかりません。equalsIgnoreCaseメソッドがJOptionPane(またはScanner)入力で機能しない

私はいくつかのことを試してみましたが、スキャナでは答えにスペースが含まれていない限り動作するように見えましたが、それはJOptionPaneとは関係なく、これは、国の首都が何であるかに関係なく機能します。

+0

'citiesarray'の値は何ですか?また、私はSOP行を 'System.out.println(" '"+ city +"' ");'のように変更して、間違ったスペースをチェックします。 –

+0

まず、あなたが答えを検証する方法は間違っています。あなたが 'citiesarray'で持っている値は何ですか?InputDialogに入力した値は何ですか? – Jobin

+0

citiesarrayの値は、* .txtファイルから読み込まれた50の州都です。 SOP行を変更すると、わからない理由のために、2番目のアポストロフィだけが出力されます。 欠けている配列の値にエスケープ文字がありますか?それは事ですか? – Lucky

答えて

0

投稿コードが完璧に働いている、私はちょうど2つの行を追加し、ループの制限を適応した後、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が宣言/初期化されています。

+0

ありがとう! 私はコードのファイル読み込み部分をどのように修正するのかは分かりませんが、Freakの提案は文字列を比較するレベルで機能しました。 – Lucky

関連する問題