gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:40:22 24 4
gpt4 key购买 nike

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

我尝试移动 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");

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

最佳答案

通过将 continue; 移动到 after catch。喜欢,

do {
System.out.println("1. Add item"); //<-- where are 2-6?
choice = sc.nextLine().charAt(0);
switch (choice) {
case '6': // <-- don't forget case '1' - '5'
try {
CarSales.ReadData();
} catch (IOException e) {
System.out.println("Error reading file '");
}
continue; // <-- here, or a break;
default:
System.out.println("Invalid Selection\n");
}
} while (choice != '6');

关于java - 一会儿如何在switch中使用try catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57839092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com