[英]how do I add a try catch block inside a for loop to catch an ArrayIndexOutOfBounds exception?
[英]how do i do input validation inside a try and catch block?
我有一个程序,用户可以在其中输入他们的姓名和名称。 它杂乱无章。 然后最后当用户输入字母而不是数字时会出现错误,我会警告“无效输入”,因此如果无效3倍,程序将关闭
到目前为止,我有这个。 我省略了一些不必要的代码,但重要的部分只是尝试,并执行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)
}
其次,在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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.