Switch 语句使第一种情况跳过一行
所以我猜这个问题的解决方案会非常简单,但我不知道我在寻找什么,所以我需要一些帮助。发生的情况是,当我运行程序并选择情况 1 时,它会打印“狗的名字”和“狗的比赛”,但没有给我机会填写狗的名字。因此,当我选择案例 1 时,我一开始只填写狗的比赛、重量和年龄!这是我正在使用的代码...
do {
System.out.println("(1 - reg\n2 - tail\n3- delete\n4-exit\nEnter number: ");
// so this is where the switch stuff starts
int option=sc.nextInt();
switch (option) {
case 1: System.out.println("Dog's Name: ");
String na=sc.nextLine();
System.out.println("Dog Race: ");
String ra=sc.nextLine();
System.out.println("How heavy?");
double wey=sc.nextDouble();
System.out.println("How old?");
double ag=sc.nextDouble();
dog doggy= new dog(na, ra, wey, ag);
kennel.add(doggy);
break;
case 2: System.out.println("its a tail");
break;
case 3: System.out.println("you delete");
break;
case 4: System.out.println("QUITTING\n(Data was not saved srry.)");
play = false;
default: System.out.println("try again");
}
}while(play);
So I'm guessing that the solution to this is going to be really simple but I have no idea what I'm looking for so I'd like some help. What happens is that when I run the program, and choose case 1. It prints both "dog's name" and "dogs race" without giving me a chance to fill in the dogs name. So when I choose case 1 I start out only getting to fill in dogs race, how heavy, and how old it is! here is the code I'm using...
do {
System.out.println("(1 - reg\n2 - tail\n3- delete\n4-exit\nEnter number: ");
// so this is where the switch stuff starts
int option=sc.nextInt();
switch (option) {
case 1: System.out.println("Dog's Name: ");
String na=sc.nextLine();
System.out.println("Dog Race: ");
String ra=sc.nextLine();
System.out.println("How heavy?");
double wey=sc.nextDouble();
System.out.println("How old?");
double ag=sc.nextDouble();
dog doggy= new dog(na, ra, wey, ag);
kennel.add(doggy);
break;
case 2: System.out.println("its a tail");
break;
case 3: System.out.println("you delete");
break;
case 4: System.out.println("QUITTING\n(Data was not saved srry.)");
play = false;
default: System.out.println("try again");
}
}while(play);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您需要在调用
nextInt()
之后调用nextLine()
,因为这尚未将扫描器推进到下一行。I believe you need to call
nextLine()
after your call tonextInt()
, because that hasn't advanced the scanner to the next line yet.第一个 sc.nextInt 有换行提醒,您可以将分隔符更改为 \n 或直接调用 nextLine();阅读选项后(使用 sc.useDelimiter("\n") )
There's a newline reminder from your first sc.nextInt, you can change the delimiter to \n or just call nextLine(); just after reading the option (Using sc.useDelimiter("\n") )
尝试:
int option=Integer.parseInt(sc.nextLine());
这具有将光标前进到下一行和获取键入的数字的效果。
Try:
int option=Integer.parseInt(sc.nextLine());
This has both the effect of advancing the cursor to the next line and getting the typed number.