猿问

如何在 switch 中使用 try catch 一会儿

一旦我运行代码来读取数据,程序执行就不会循环回来。


我尝试改变放置 try catch 语句和finally 语句的位置,并且所有中断方式都会继续。


    long code;

    char choice;



    Cars CarSales = new Cars(); //It creates a Java object and allocates memory for it on the heap.

    Scanner sc = new Scanner(System.in);


    System.out.println("   -----CARS SALES YARD------"); //The println is a method of java.io.PrintStream.

    do {

        System.out.println("1. Add item");

        choice = sc.nextLine().charAt(0);

        switch (choice) {     //switch statement allows a variable to be tested for equality against a list of values. 

        case '6':

            try{

            CarSales.ReadData();

            continue;

            }

            catch(IOException e){

                     System.out.println("Error reading file '" );

                     continue;

            }

        default:

            System.out.println("Invalid Selection\n");

        }

    } while (choice != '6'); //while loop statement repeatedly executes a statement as long as a given condition is true

    sc.close();


public void ReadData() throws IOException{//This Method is in the Cars class

String fileName = "input.txt";

String line = null;

FileReader fileReader = new FileReader(fileName);

BufferedReader bufferedReader = new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) {

            System.out.println(line);

    }   

bufferedReader.close();   

System.out.println("TRY");

尽管程序执行只是停止循环,但没有错误消息。


当年话下
浏览 133回答 1
1回答

慕运维8079593

通过continue;将移至后catch。喜欢,do {&nbsp; &nbsp; System.out.println("1. Add item"); //<-- where are 2-6?&nbsp; &nbsp; choice = sc.nextLine().charAt(0);&nbsp; &nbsp; switch (choice) {&nbsp; &nbsp; case '6': // <-- don't forget case '1' - '5'&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CarSales.ReadData();&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Error reading file '");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; continue; // <-- here, or a break;&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Invalid Selection\n");&nbsp; &nbsp; }} while (choice != '6');
随时随地看视频慕课网APP

相关分类

Java
我要回答