2017-11-02 1 views
0

スキャナのユーザ入力が複数ある場合、スキャナは文字列全体をスペースでどのように読み取ることができますか?私は複数回答Scanner.nextLine()を使用することをお勧め見てきたが、私は int choice = in.nextInt()空白文字列を含む異なる入力タイプの連続したネストされたスキャナ

public static void main (String[] args){ 
Scanner in = new Scanner(System.in); 
System.out.println ("welcome to November 1st Homework choices! if you would like to test the SSN condenser, input 1! if you would like to test the 'a' counter, input 2! If you would like to test both, enter 3!"); 
int choice = in.nextInt(); 
switch(choice){ 
    ... 
    case 2: 
    System.out.println("Please input a phrase of any sort to count the number of 'a''s in the phrase! :)"); 
    String phrase = in.next(); 
    System.out.println("The number of 'a's in the phrase is " + CountA(phrase)); 
    break; 
    case 3: 
    ... 
    System.out.println("Please input a phrase of any sort to count the number of 'a''s in the phrase! :)"); 
    String phrase2 = in.next(); 
    System.out.println("The number of 'a's in the phrase is " + CountA(phrase2)); 
    break; 
    default: 
    System.out.println("YOU MUST ENTER A NUMBER BETWEEN 1 AND 3!! >:(D--"); 
    break; 
} 

(私はswitch, case代わりif/elseの使用理由である)の入力にchoiceための整数と同じ行に文字列phraseを持っている必要はありません}

私は私の質問を明確にしたいと思う、私はかなり混乱している。

Using String phrase = in.nextLine(); this is the 2 outputs

+0

なぜ同じ行に選択肢とフレーズを入力する必要がありますか? – luckydog32

+0

同じように選択し、それぞれのswitch文でこの行を変更します: 'String phrase = in.nextLine();' – luckydog32

+0

現在のコードの実際の問題は何ですか? –

答えて

0

あなたがこの問題を抱えている理由は、あなたが作成され、最初の外出先でnextLine()以外の他のスキャナ法によってピックアップされていない「見えない」改行文字がありますエンターキーを押したとき。あなたはそれについてもっと読むことができますhere

あなたは3を入力してEnterキーを押します。スキャナキューは次のようになります。

"3\n" 

その後、あなたはin.next();を使用しています。スキャナは数値を取りますが、新しい行の文字の葉:

"\n" 

だから、あなたのString phrase = in.next();に着きます。入力として新しい行のcharが使用されます。

解決策は、nextLine()でキャッチし、何もしないことです。あなたのコードでは次のようになります:

int choice = in.nextInt(); 
in.nextLine(); //catch new line char 
関連する問題