java Try catch in switch语句退出选项
我遇到的问题是,当我键入0作为菜单选项(即退出程序的选项)时,输出为:
无效选择,请输入菜单选项编号0-10
感谢您使用成绩册程序,祝您有愉快的一天
当它应该只显示感谢您使用程序消息而不是无效选择消息时
这是我的密码:
import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Tester
{
public static void main(String[] args) throws IOException
{
Scanner kbReader = new Scanner (System.in);
boolean loop = true;
int choice = 0;
Student array[] = null;
System.out.printf("%50s", "Welcome to the Gradebook Program!");
while(loop){
do
{
try
{
choice = Student.printMenu();
int numStudents;
switch(choice)
{
case 1:
Gradebook.classInfo();
numStudents = Gradebook.getNumStudents();
array = Student.inputStudents(numStudents);
Student.printGrades(array);
break;
case 2:
array = Student.addStudent(array);
Student.printGrades(array);
break;
case 3:
int target = Student.getStudentToDelete(array);
array = Student.deleteStudent(array, target);
Student.printGrades(array);
break;
case 4:
Student.editStudent(array);
Student.printGrades(array);
break;
case 5:
Student.printGrades(array);
break;
case 6:
array = Student.inputGrades();
break;
case 7:
Student.outputToFile(array);
break;
case 8:
Student.search(array);
break;
case 9:
Student.studentHighest(array);
break;
case 10:
Student.assignmentHighest(array);
break;
default:
System.out.println("\nInvalid choice, please enter a menu option number 0-10");
}
}
catch(InputMismatchException e)
{
System.out.println("Error: Invalid input, please enter a menu option number 0-10");11
}
}
while(choice != 0);
loop = false;
System.out.println("\nThank you for using the Gradebook Program, have a nice day.");
}
}
}
# 1 楼答案
您需要向交换机添加
case 0:
选项:添加
case 0
选项将阻止它进入开关中的默认情况。然后它将退出循环,显示“谢谢”消息,然后退出# 2 楼答案
switch语句没有
case 0:
。因此,它被引导到默认情况。之后的逻辑是确认0并退出循环正如我打字时在评论中提到的