首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在try和catch块中进行输入验证?

问如何在try和catch块中进行输入验证?
EN

Stack Overflow用户
提问于 2017-03-28 01:40:45
回答 1查看 98关注 0票数 0

我有一个程序,用户可以输入他们的名字和东西。它是一个很大的尝试支架。然后在最后,当用户输入字母而不是数字时,它会被捕获,这会警告“无效输入”。我想这样做,如果它无效3倍,程序就会关闭

到目前为止,我已经有了这个。我省略了一些不必要的代码,但重要的部分是try,and do while循环

代码语言:javascript
复制
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)
    }
EN

回答 1

Stack Overflow用户

发布于 2017-03-28 01:53:37

  • 你需要添加一个else,在你的选项的底部选择part。
  • 好的做法是将它强制转换为int,因为用户可以输入带有前导空格的零,这仍然是在catch in finally块之后关闭文件(关闭所有可关闭的资源)

int尝试= 0;布尔验证= false;do { input_option = input.nextLine();try {整数选项= Integer.valueOf(input_option);开关( option ) {案例0: System.out.println(“输入您的名字");字符串firstnameopt0 = input.nextLine();System.out.println(”输入您的姓氏");String lastnameopt0 = input.nextLine();break;案例1: System.out.println(“输入您的名字");String firstnameopt1 = input.nextLine();break;案例2: System.out.println(”输入您的名字");String firstnameopt2 = input.nextLine();break;default: attempt++;System.out.println(“必须输入整数”);}} catch (Exception ex) {System.out.println(“必须输入整数”);attempt++;}} while (attempt <3 && authenticated == false);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43053075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档