while(flag)
{
System.out.println("Press 1 to Add Student details");
System.out.println("Press 2 to Display Student details");
System.out.println("Press 3 to Sort");
System.out.println("Press 4 to Search");
System.out.println("Press 5 to Exit");
System.out.println("Enter your choice: ");
while(!sc1.hasNextInt())
{
System.out.println("Please enter proper Integer input!");
sc1.next();
}
choice = sc1.nextInt();
//more code..
}
在上面的代码中,我正在接受用户的输入。如果用户输入除int之外的任何内容,则不接受。假设,给出一个字符串而不是int,打印消息并且不再显示菜单。我想在消息后显示菜单。我该怎么做?
答案 0 :(得分:1)
这可能对您有所帮助
while (flag) {
System.out.println("Press 1 to Add Student details");
System.out.println("Press 2 to Display Student details");
System.out.println("Press 3 to Sort");
System.out.println("Press 4 to Search");
System.out.println("Press 5 to Exit");
System.out.println("Enter your choice: ");
if (sc1.hasNextInt()) {
choice = sc1.nextInt();
//more code here
} else {
System.out.println("Please enter proper Integer input!\n");
sc1.next();
}
}
我添加了额外的"\n"
以提高可读性。因此,当打印警告时,选项将不会在下一行打印。
答案 1 :(得分:0)
您还需要在内部循环中使用菜单sysouts。像这样: -
while(!sc1.hasNextInt())
{
System.out.println("Please enter proper Integer input!");
System.out.println("Press 1 to Add Student details");
System.out.println("Press 2 to Display Student details");
System.out.println("Press 3 to Sort");
System.out.println("Press 4 to Search");
System.out.println("Press 5 to Exit");
System.out.println("Enter your choice: ");
sc1.next();
}