【问题标题】:Try catch in switch statement exit option尝试在 switch 语句退出选项中捕获
【发布时间】:2018-02-19 20:56:48
【问题描述】:

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

【问题讨论】:

  • 在您的switch 中添加case 0: break;
  • 那么while语句会变成什么?
  • 不会。添加case 0 选项将阻止它转到开关中的default 大小写。然后它会退出循环,显示“谢谢”消息,然后退出。

标签: java arrays loops switch-statement try-catch


【解决方案1】:

您需要为您的交换机添加一个case 0: 选项:

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

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

【讨论】:

    【解决方案2】:

    switch 语句没有case 0:。因此,它被指向默认情况。之后的逻辑就是确认 0 并退出循环。

    正如我在输入时在 cmets 中提到的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多