java - 在 switch 语句退出选项中尝试 catch

标签 java arrays loops switch-statement try-catch

我遇到的问题是,当我输入 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.");
}
}
}

最佳答案

您需要向您的开关添加 case 0: 选项:

switch(choice)
{   
    case 0: break;
    case 1: ...
        break;
    ...
}

添加 case 0 选项将阻止它转到开关中的默认情况。然后它将退出循环,显示“谢谢”消息,然后退出。

关于java - 在 switch 语句退出选项中尝试 catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48874050/

相关文章:

java - 防止 Java 序列化设置默认值

PHP:如何在支持属性的情况下将数组转换为 XML(DOMi?)

python - 根据另一个数组中包含的索引有效地求和 4D 数组

JavaScript 映射和过滤基本对象数组

c - 找到最长且不重复的子数组

javascript - 在 JavaScript 中分离 while 循环输出

java - 除了覆盖算术运算符之外,还有其他方法可以在 Java 中实现 "overflow safe"算术运算吗?

java - 是否可以在不关闭流的情况下关闭阅读器?

java - 如何在hibernate条件中使用mysql的 "use index()"子句?

C# Get 访问器不可访问