java - 好奇为什么这个递归代码不起作用,并且在另一种方法中表现出非常相似的行为

标签 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; 
}

这里的第一个方法显然只是一种求和的方法。我知道有很多其他方法可以将一些数字加在一起,我自己也做过一些,但是当我的类(class)上完关于方法的课并将其写成类似我列出的代码之类的东西时,我首先想到的是作为解决方案,而不是老师最终推荐的。无论如何,我认为这将是一个很好的学习练习。

这段代码在 Eclipse 中没有显示任何错误,所以我很困惑为什么它拒绝工作。事实上,它产生的结果我真的很好奇;它自然会在程序开始时要求输入,但是当我输入 0、1 或任何其他 int 时,尽管扫描仪实际上有一个整数,但会打印“Integers only please”,然后 Java 在程序末尾宣布异常while 循环、goodInput 调用 sum 时、c 返回时、main 方法中 sum 执行时、以及 java.util.NoSuchElementException、java.util.Scanner. throwFor 和 java.util 处。扫描仪.下一个。

我不太清楚这里发生了什么;我最好的猜测是内存问题,但错误从一开始就开始出现!当goodInput 中的代码仅用作main 方法时,效果非常好;不确定为什么通过 sum 调用它会导致问题。

再说一遍,我不只是想要一些求和方法。我只是想知道为什么代码会以这种方式运行,以及使用我的方法实现 sum 实际上是如何工作的。

最佳答案

这里的问题不是递归,而是您的扫描仪。我不得不承认我对 Scanner 类不太熟悉,但似乎如果你调用 input.close() 然后重新输入 goodInput 稍后,您的 System.in 将关闭。至少,通过调试器进行单步调试,我发现“仅使用整数”这一行在 goodInput 的第二次调用中打印出来。删除 input.close(); 行对我来说很有效,并且您的方法按预期工作。

我建议您在主方法中初始化扫描仪,将其作为参数传递,然后在主方法中关闭它。

编辑: Scannerclose 方法声明如下:

If this scanner has not yet been closed then if its underlying java.lang.Readable readable also implements the java.io.Closeable interface then the readable's close method will be invoked.

因此,当您在 Scanner 上调用 close 时,底层读取器(即 System.in)已关闭。

关于java - 好奇为什么这个递归代码不起作用,并且在另一种方法中表现出非常相似的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25963718/

相关文章:

java - 如何在 mac 上从 java 读取和写入原始 ip 数据包?

java - ILOG TSP 得到空输出

java - 为什么我使用递归时会出现此错误?

java - 在 Java 中从 MM/DD/YYYY 到 DD-MMM-YYYY

java - Selenium Webdriver 中的前端数据验证

javascript - 递归 ajax() 请求

recursion - 生成递归和结构递归有什么区别?

java - 用户输入导致表单出现

c++ - 从输入文件中读取并存储在数组 C++ 中

javascript - jQuery if 语句触发两次