【问题标题】:recursive method asking for an integer from 1 to 10递归方法要求从 1 到 10 的整数
【发布时间】:2014-09-24 02:44:49
【问题描述】:

我正在尝试编写一个方法,该方法应该递归地要求用户输入一个从 1 到 10 的值。

这就是我所拥有的:

public static void main(String[] args) {


    int value = readGoodInput();
     System.out.println("The user entered: " + value);

}

public static int readGoodInput(){

    int value;
    Scanner input = new Scanner(System.in);
    System.out.println();

    System.out.println("Enter a value: ");
    value = input.nextInt();

    if (value <= 10 && value >= 1){

        return value;       
    }
    else{

        readGoodInput();

    }
    return value;

}

当我运行程序时:

输入一个值: 11

输入一个值: 22

输入一个值: 3

用户输入:11

我的问题是:为什么最后打印的值不是 3,即 1 到 10 之间,而是 11?

提前谢谢你,

滴滴

【问题讨论】:

  • 这不是对递归的适当使用。这门课的教练要求你这样做吗?
  • 哦,是的......不幸的是。
  • 为什么,为什么,为什么,为什么,为什么,为什么,为什么,为什么 ...教师无法弄清楚如何在不强迫学生写出可怕的东西的情况下教授递归代码...

标签: java recursion methods


【解决方案1】:

需要返回值:

else {
    return readGoodInput();
}

否则代码会被执行,但永远不会返回“好的输入”,只会返回第一个。

【讨论】:

  • 这修复了 OP 的问题,但没有解释问题。
【解决方案2】:

您必须仔细遵循您的递归。查看递归发生的位置以及返回的值。请参阅下面的 cmets 作为指南。

在接下来的递归调用中,您的第一个递归值永远不会改变。因此第一次使用的值将是main方法中显示的值。

public static void main(String[] args) {


    int value = readGoodInput();
     System.out.println("The user entered: " + value);

}

public static int readGoodInput(){

    int value;
    Scanner input = new Scanner(System.in);
    System.out.println();

    System.out.println("Enter a value: ");
    value = input.nextInt();

    if (value <= 10 && value >= 1){
        // readGoodInput()3 returns value of 3 to readGoodInput()2
        return value;       
    }
    else{
        // readGoodInput()1 returns value of 11 to main's readGoodInput()
        // readGoodInput()2 returns value of 22 to readGoodInput()1

        readGoodInput();  // This is where your recursion happens.


    }

    return value; // This will return the first readGoodInput() value.

}

如果您希望它在递归完成后返回 3... 将您的值 = 设置为递归方法。

        else{
        value = readGoodInput();  // This is where your recursion happens.


    }

【讨论】:

  • 为什么最终返回值;返回第一个 readGoodInput() 值?
  • 将每个递归视为其自身的情况。
  • 还要注意它不是value = readGoodInput() 我以前实际上被这类问题难住了。
  • 我已经调整了我的答案来解释你的下一个问题。
【解决方案3】:

您不需要进行递归,您可以通过使用 while 循环来实现这一点,因为它是一个非常简单的操作。

但如果你有更多的逻辑要放入该函数中,那么可能需要递归。

public static int readGoodInput(){

    int value = 0;
    Scanner input = new Scanner(System.in);

    while(value < 1 || value > 10){
         System.out.println("Enter a value: ");
         value = input.nextInt();
    }

    return value;
}

【讨论】:

    猜你喜欢
    • 2013-05-23
    • 2015-07-03
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    相关资源
    最近更新 更多