繁体   English   中英

我如何在try and catch块内进行输入验证?

[英]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)
    }
  • 您需要添加一个else,在选项底部选择部件。
  • 优良作法是将其强制转换为int,因为用户可以输入零且前导空格仍然有效。
  • 其次,在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM