那里会有多少位客人? 4
输入客人1的选择
输入客人2的选择
输入宾客数后,宾客1和2彼此落在了一起,而没有给我输入宾客1的选择的机会,宾客2进入了宾客2。 我该如何解决?
public static void main(String[] args) {
Scanner simpleInput= new Scanner (System.in);
int guest;
String choice;
System.out.println("Welcome to Tying the Knot Wedding Planner Guide");
System.out.println();
System.out.println("For each guest, please enter he/her choice for dinner: Beef, Chicken, Fish, or\r\n" +
"Vegetarian.\r\n" +
"");
System.out.print("How many guests will there be there? ");
guest=simpleInput.nextInt();
while (guest <0 )
{
System.out.println ( "That was not a valid number, try again. " );
System.out.println("How many guests will there be there? ");
guest=simpleInput.nextInt();
}
for (int x = 1; x < guest; x++ )
{
System.out.println("Enter the choice for guest " + x);
choice=simpleInput.nextLine();
}
System.out.println("There will be " + guest + " meals");
}
答案 0 :(得分:0)
请从
更改您的代码guest=simpleInput.nextInt();
到
guest=Integer.parseInt(simpleInput.nextLine());
这将帮助您解决问题
答案 1 :(得分:0)
当您使用方法.nextInt(
时,扫描器将读取并解析文本,直到换行符(\ n),因此,当再次尝试使用任何读取方法时,扫描器将不为空(具有\ n个字符),这就是为什么它假定用户确实输入了另一个字符串的原因
您可以通过多种方式克服这一问题,一种方法是,只需在.nextInt()
simpleInput.nextline();
其他方法是先获取整行,然后再解析出int,不保留/ n字符
guests = Integer.parseInt(simpleInput.nextLine());