【发布时间】:2015-07-18 14:57:01
【问题描述】:
我有一些代码涉及检查用户输入以查看输入的输入是字符串还是 int,并且会根据结果执行不同的代码。我正在使用 Integer.parseInt 来确定用户输入是否为整数,如果不是则抛出 NumberFormatException。
但是,为了控制代码流,我使用了 try/catch 语句,catch 块用于包含在用户输入是字符串(即 NumberFormatException)时将运行的代码.
Qn
这是使用 try/catch 块的可接受方式吗?我试过用谷歌搜索这个,但我能找到的只是用来处理抛出的异常而不是像我一样使用的 catch 块的例子。
import java.io.*;
import java.util.*;
public class Datafile{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Kence\\workspace\\Java 8 - Beyond the Basics - Working Files\\Practice Programs\\src\\Practice Data Edited",true));
String data = null;
boolean end = false;
boolean cont = true;
String dataEntered = null;
int menuChoice = printMenu();
while(!end){
switch(menuChoice){
case 1:
System.out.println("Please enter a line of data or press 0 to exit back to the main menu");
dataEntered = input.nextLine();
try {
if(Integer.parseInt(dataEntered) == 0){
break;
}
} catch (Exception e) {
data += dataEntered + "\n";
while(cont){
System.out.println("Data entered.Please enter the next line of data or press quit to exit back to the main menu.");
dataEntered = input.nextLine();
if(Integer.parseInt(dataEntered) == 0){
cont = false;
break;
}else{
data+= dataEntered;
System.out.println("Current data entered is " + dataEntered);
}
}
}
break;
case 2:
System.out.println("2 Entered");
break;
case 3:
System.out.println("3 Entered");
break;
case 4:
System.out.println("4 Entered");
break;
}//End of switch statement
menuChoice = printMenu();
}
input.close();
}//End of main
public static void printStars(){
for(int i = 0; i<66 ; i++){
System.out.print("*");
}
System.out.println();
}
public static int printMenu(){
printStars();
System.out.println("System Started");
printStars();
System.out.println("Enter 1 to input a new line of data");
System.out.println("Enter 2 to list all data");
System.out.println("Enter 3 to save existing data");
System.out.println("Enter 4 to load data");
printStars();
return Integer.parseInt(input.nextLine());
}
}
【问题讨论】: