Jos*_*man 2 java recursion input while-loop
这里是新程序员,对于我认为递归的一些代码存在一些问题.
public static int sum (int a) {
int input = goodInput(); //get input from below method without having to put its code in this one
if (input==-1)//so user has the ability to exit at any time
return a; //when user has finally entered -1, the final sum is sent out
else; //for scenarios before last input
int b = a + input; //adding the newest input to the sum
int c = sum(b); //throw the total into the method again until -1 is read
return c; //once -1 is read, a in that iteration is sent up through every iteration of the method until the original method gets its return
}
public static int goodInput () { //code to get input of correct type
Scanner input = new Scanner (System.in);
while (!input.hasNextInt()) { //if I put in integer input, the loop should not be entered, but this isn't happening
System.out.println("Integers only please");
input.next();
}
int finalInput = input.nextInt(); //Finally set good input
input.close(); //close scanner
return finalInput;
}
Run Code Online (Sandbox Code Playgroud)
这里的第一种方法显然只是获得总和的一种方法.我知道有很多其他的方法可以将一些数字加在一起,我自己做了一些,但是当我的课上有关于方法的教训并写下类似我列出的代码之类的东西是我能想到的第一件事作为一种解决方案,而不是教师最终推荐的内容.无论如何,认为这将是一次很好的学习练习.
这段代码在eclipse中没有显示任何错误,所以我很难理解为什么它拒绝工作.确实,它产生了我真正好奇的结果; 它自然地在程序开头询问输入,但是当我输入0,1或任何其他int时,尽管扫描仪实际上有一个整数,但是打印出"仅使用整数",然后Java在结束时宣布例外. while循环,在goodInput的调用中,在返回c时,在main方法中执行sum,以及在java.util.NoSuchElementException,java.util.Scanner.throwFor和java.util中. Scanner.next.
我不知道这里发生了什么; 我最好的猜测是内存问题,但错误在第一次出现时就开始了!并且goodInput中的代码在用作主方法时效果很好; 不确定为什么被sum调用会导致问题.
同样,我不只是想要一些求和方法.我只是想知道代码为什么会以这种方式运行,以及如何实现与我的方法相加的实际工作.
不是递归是这里的问题,但你的Scanner.我不得不承认我对这门Scanner课程并不太熟悉,但似乎如果你打电话input.close()然后再重新进入goodInput,你System.in就会被关闭.至少,通过调试器,我发现第二次调用时打印出"仅请整数"行goodInput.删除该行input.close();对我来说很有用,而且你的方法按预期工作.
我建议您在main方法中初始化扫描程序,将其作为参数传递,然后在main方法中关闭它.
编辑:状态的close方法Scanner如下:
如果此扫描程序尚未关闭,那么如果其底层java.lang.Readable可读也实现了java.io.Closeable接口,那么
close将调用可读的方法.
因此,潜在的读者,即System.in,是当你叫封闭close的Scanner.