私は、ユーザに名前を入力してリストに格納し、年齢を入力して別のリストに格納するように要求するコードを記述しようとしています。その後、ユーザーに再試行するかどうかを尋ねる[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?
}
}
}
私はあなたの助けに感謝します。ありがとうございました。
ヒント: 'repeat = scan.next()'の行で受け取った内容を確認しましたか? "123 XYZ"を年齢として入力するようなことに注意してください。 –