2016-09-26 17 views
0

私は、ユーザに名前を入力してリストに格納し、年齢を入力して別のリストに格納するように要求するコードを記述しようとしています。その後、ユーザーに再試行するかどうかを尋ねる[Y/N]。 コードをテストするとき、私は "Y"を入力し、別の名前を入力するようにループに期待しました。代わりに、名前入力をスキップして年齢入力にジャンプします。なぜ私は理解できません。 コードはこちらこのループの2回目の繰り返しが最初のスキャンをスキップするのはなぜですか?

import java.util.ArrayList; 
import java.util.Scanner; 

public class PatternDemoPlus { 
    public static void main(String[] args){ 
     Scanner scan = new Scanner(System.in); 
     ArrayList<String> names = new ArrayList<String>(); 
     ArrayList<Integer> ages = new ArrayList<Integer>(); 
     String repeat = "Y"; 
     while(repeat.equalsIgnoreCase("Y")){ 
      System.out.print("Enter the name: "); 
      names.add(scan.nextLine()); 
      System.out.print("Enter the age: "); 
      ages.add(scan.nextInt()); 

      System.out.print("Would you like to try again? [Y/N]"); 
      repeat = scan.next(); 
      //Notice here that if I use "repeat = scan.nextLine(); instead, the code does not allow me to input anything and it would get stuck at "Would you like to try again? [Y/N] 
      System.out.println(repeat); 

      //Why is it that after the first iteration, it skips names.add and jumps right to ages.add? 
     } 
    } 
} 

私はあなたの助けに感謝します。ありがとうございました。

+0

ヒント: 'repeat = scan.next()'の行で受け取った内容を確認しましたか? "123 XYZ"を年齢として入力するようなことに注意してください。 –

答えて

0

next()を使用すると、スペースの前に来るものだけが返されます。 nextLine()は、現在の行を返した後にスキャナを自動的に下に移動します。

以下のようにコードを変更してください。

public class PatternDemoPlus { 
    public static void main(String[] args){ 
     Scanner scan = new Scanner(System.in); 
     ArrayList<String> names = new ArrayList<String>(); 
     ArrayList<Integer> ages = new ArrayList<Integer>(); 
     String repeat = "Y"; 
     while(repeat.equalsIgnoreCase("Y")){ 
      System.out.print("Enter the name: "); 
      String s =scan.nextLine(); 
      names.add(s); 
      System.out.print("Enter the age: "); 
      ages.add(scan.nextInt()); 
      scan.nextLine(); 
      System.out.print("Would you like to try again? [Y/N]"); 
      repeat = scan.nextLine(); 

      System.out.println(repeat); 


     } 
    } 
} 
+1

あなたはこの回答を与える前に "Bill Murray"という名前を入力しようとしたことがあります:) –

+0

申し訳ありませんが、私は他のコードを入れました...今すぐ更新しました –

+0

私のコードのコメントの1つに、 //ここでは、 "repeat = scan.nextLine();を使用すると、コードで何か入力することができず、"もう一度やり直しますか? [はい/いいえ] – dou2abou

関連する問題