我有一个程序,用户可以输入他们的名字和东西。它被认为是一个很大的尝试。然后在最后它有一个捕获当用户输入字母而不是数字时会有警告“无效输入”我想这样做如果它无效3x,程序关闭
到目前为止,我有这个。我省略了一些不必要的代码,但重要的部分只是尝试,并做while循环public static void main(String[] args) throws FileNotFoundException {
try{
Scanner input = new Scanner(System.in);
String input_option = "1";
// calling option method
print_options();
int attempt= 0;
boolean authenitcated = false;
do{
input_option = input.nextLine();
if (input_option.equals("0")) {
System.out.println("Enter your first name ");
String firstnameopt0 = input.nextLine();
System.out.println("Enter your last name ");
String lastnameopt0 = input.nextLine();
type.println("Annual Income: " + income);
type.println("Tax: " + opt0tax);
myfile.exists();
type.close();
}
else if (input_option.equals("1")) {
System.out.println("Enter your first name ");
String firstnameopt1 = input.nextLine();
type.close();
}
else if (input_option.equals("2")) {
System.out.println("Enter your first name ");
String firstnameopt2 = input.nextLine();
myfile.exists();
type.close();
}
//extra_options();
input.close();
catch(InputMismatchException exi){
System.out.println("you must enter a double");
attempt++;
}
}while(attempts < 3 && authenticated == false)
}
答案 0 :(得分:0)
其次在finally块中的catch(关闭所有可关闭的资源)之后关闭文件
int attempt = 0;
boolean authenticated = false;
do {
input_option = input.nextLine();
try {
Integer option = Integer.valueOf(input_option);
switch (option) {
case 0:
System.out.println("Enter your first name ");
String firstnameopt0 = input.nextLine();
System.out.println("Enter your last name ");
String lastnameopt0 = input.nextLine();
break;
case 1:
System.out.println("Enter your first name ");
String firstnameopt1 = input.nextLine();
break;
case 2:
System.out.println("Enter your first name ");
String firstnameopt2 = input.nextLine();
break;
default:
attempt++;
System.out.println("you must enter a int");
}
} catch (Exception ex) {
System.out.println("you must enter a int");
attempt++;
}
} while (attempt < 3 && authenticated == false);