java - 一会儿如何在 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");
尽管程序执行只是停止循环,但没有错误消息。
解决方案
通过将continue;
移到之后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');
推荐阅读
- dotnetnuke - 2Sxc 新闻应用程序视图配置更改未应用于公共视图。如何公开应用视图配置?
- javascript - 使用 es5 将定义好的字符串格式化为对象
- prometheus - 使用 Prometheus 监控容器 CPU 利用率
- python - Pyspark - 基于前一行值的增量值
- azure - 如果我们将 `DisableCustomAppAuthentication` 设置为 true,则针对 SharePoint Online 验证我们的 .NET 控制台应用程序
- python - .coeff() 没有给出正确答案 Python Sympy
- java - 为什么我在android中放入MutableLiveData后会得到Null
- api - 注销不会撤销 OneLogin OpenId Connect 中的令牌
- javascript - 将 javascript 对象从一个 React 组件发送到另一个
- javascript - 将悬停状态添加到以 Javascript 为目标的类