Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中处理用户输入类型?_Java - Fatal编程技术网

如何在java中处理用户输入类型?

如何在java中处理用户输入类型?,java,Java,如果我的程序中允许的输入仅为int类型,但它们使用户可以任意键入不允许的类型字符,例如double或char等。我如何处理?我肯定会有这样的抛出异常之类的事情,但我只是不确定它是如何做到的。如有任何建议,将不胜感激 //here is my code System.out.print("Too " +additionalInfo+ "! Try again: "); attemptCounter++; int x= input.nextInt(); // here is where i want

如果我的程序中允许的输入仅为
int
类型,但它们使用户可以任意键入不允许的类型字符,例如
double
char
等。我如何处理?我肯定会有这样的
抛出异常
之类的事情,但我只是不确定它是如何做到的。如有任何建议,将不胜感激

//here is my code
System.out.print("Too " +additionalInfo+ "! Try again: ");
attemptCounter++;
int x= input.nextInt(); // here is where i want the usr to type in their input

使用循环在无效输入后再次提示用户输入,例如

    int userInput;
    while(true) {    
        try {
            System.out.println("Please enter a number: ");
            Scanner input = new Scanner(System.in);
            userInput = input.nextInt();
            break;
        }
        catch(InputMismatchException | NumberFormatException ex ) {
            System.out.println("Invalid Number, Please try again");
        }
    }

声明:Throws:InputMismatchException-如果下一个标记与整数正则表达式不匹配,或超出范围。通过阅读你的课本来学习异常,或者如果你因为我链接了异常教程而如此爱我,那么你应该学会爱谷歌。通常,在Google中键入“java教程”会直接导致上的java教程。键入“SomeClass java api doc”直接导致SomeClass的javadoc。或者您可以将javadoc主页添加书签,并浏览包和类。学会自主。