else if(digit == 2)
{
System.out.print("Enter the name of artist : ");
String artist=input.nextLine();
System.out.print("Enter the song title : ");
String song = input.nextLine();
System.out.print("Enter the number of week :");
int oldWeek =input.nextInt();
System.out.print("Enter the new number of week :");
int newWeek =input.nextInt()
}
您好,我正在运行一个else if循环,如果用户输入2将运行以下代码,但问题似乎是在运行时它会同时运行2 System.out.println
个代码。这是我输出的样本
This program will display singles that was Number one on charts
Enter 1 or 2. 2
Enter the name of artist : Enter the song title :
答案 0 :(得分:3)
好像你在nextInt()
之前执行了nextLine()
。会发生什么是nextInt()
不消耗新行字符,因此下一个nextLine()
将使用它。这使nextLine()
被忽略了。的 For further information you could see this entry. 强>
一种解决方案是在nextLine()
之后调用nextInt()
以使用换行字符:
int number = scanner.nextInt();
scanner.nextLine(); // Just to consume new-line character
...
另一个解决方案是使用nextLine()
读取整数,然后用Integer.parseInt()
解析它:
int number = Integer.parseInt(scanner.nextLine());
...