2011-12-26 23 views
0

次のコードでは、yをキーボードに入力すると、分岐ステートメントのelse部分が入力されます。何故ですか?Java入力が文字列を認識しない

public static void getInput(){ 
    String response; 
    String[] coins = new String[6]; 

    System.out.println("Would you like to enter your own amount? (y/n)"); 

    Scanner sc = new Scanner(System.in); 
    response=sc.nextLine(); 

    if (response=="y"){ 
     System.out.println("You entered y"); 
     } 
    else{ 
     System.out.println("You did not enter y, you entered " + response); 
     } 
    } 
+0

あなたは...このプログラムに – Vinoth

答えて

2

あなたはresponse.equals( "y")が必要です。

+0

感謝をメインクラスを持っていない...多分私は最終的にこのようなものを学びます:) – Geekender

+0

それは作るのは簡単間違いです。 –

1

問題は状態if(response=="y")です。

equals()メソッドは、Stringオブジェクト内の文字を比較します。 ==演算子は、2つのオブジェクト参照が同じインスタンスを参照しているかどうかを比較します。

使用

(response.equals("y") 
関連する問題