Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/383.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函数从扫描仪获取输入直到int?_Java_Input_Io_Int_Java.util.scanner - Fatal编程技术网

Java函数从扫描仪获取输入直到int?

Java函数从扫描仪获取输入直到int?,java,input,io,int,java.util.scanner,Java,Input,Io,Int,Java.util.scanner,我试图创建一个java函数,返回用户输入的int,但在用户输入有效数字之前不会返回。以下是我的函数初始模型: public int getChoice(){ try{ return scan.nextInt(); }catch(Exception e){ return getChoice(); } } scan由Scanner scan=新扫描仪(System.in)声明 这个函数产

我试图创建一个java函数,返回用户输入的
int
,但在用户输入有效数字之前不会返回。以下是我的函数初始模型:

    public int getChoice(){
        try{
            return scan.nextInt();
        }catch(Exception e){
            return getChoice();
        }
    }
scan
Scanner scan=新扫描仪(System.in)声明

这个函数产生了一个
Java.lang.StackOverflowerError
(嗯……这似乎是一个合适的网站……)。我想这是因为函数不断被调用

我曾考虑过使用
Integer.valueOf(scan.nextLine())”
,但我没有真正使用它的原因是,在某些情况下,我不知道是什么决定了是否会发生这种情况,但当程序调用
nextLine()
时按“Enter”将跳过下一个
nextLine()
。我真的想不出一个解决办法


因此,如果有人可以为我提供一个Java函数,该函数将循环直到用户输入一个有效的整数,然后返回该整数,请这样做,谢谢。

您得到了一个错误的递归,因为getChoice调用在catch块内。要无限期地重复代码直到用户给您一个有效数字,请使用
while(true)
infinite循环。代码您必须读取该行并将其转换为整数,这很好

public int getChoice() {       
    while (true) {
        try {                                
            return Integer.valueOf(scan.nextLine());
        } catch (Exception e) {
            System.out.println("Enter a valid number");
        }
    }
}

您可以重写代码而不使用递归来查看发生了什么:将其放入
while(true)
循环中,并删除对
getChoice()
的调用-返回将中断循环,如果出现异常,它将重复。