【问题标题】:Getting positive integer using recursion使用递归获取正整数
【发布时间】:2016-11-15 00:19:55
【问题描述】:

我很困惑,我想使用递归从用户那里得到一个正整数,用户可以输入单词,也可以输入数字。(单词和负数是无效的),不知道我做错了什么。 很抱歉忘了问这个问题,我遇到编译器错误,当我尝试编译它时,我的扫描仪有问题,我正在阅读它说我必须为用户输入使用参数,我'不知道怎么做,第二个问题是,如果用户输入 n

import java.util.*;

public class Recursion {


private static int getPositiveInt(Scanner keyboard) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a positive interger, n");
int n = keyboard.nextInt();


  if (n > 0) {

  return n;
}
 else { //here the code  should rerun if invalid input, but I cant figure it     out
System.out.println("enter a positive number");
} 
}
}

【问题讨论】:

    标签: recursion


    【解决方案1】:

    如果我正确理解了您的问题,您希望此函数运行,直到它读取一个有效数字。 为此,您需要更改的是:

    else { //here the code  should rerun if invalid input, but I cant figure it     out
    System.out.println("enter a positive number");
    }
    

    到:

    else { 
    //call the function again
    return getPositiveInt(Scanner keyboard)
    }
    

    【讨论】:

    • 谢谢,所以当用户输入除正整数以外的任何内容时,它会运行此程序?
    • 这是个问题吗?你能再解释一下这个问题吗?
    • 好的,所以这个程序的重点是使用递归向用户询问一个正整数。用户可以输入诸如 -10、0 或单词“car”之类的内容。如果用户输入 n
    • Tour 问题是您正在以整数形式读取输入,但不确定是否是整数。 nextInt() 调用会抛出异常
    • 抱歉消息被拆分了,我不小心点击了回车按钮,它发送了评论而没有让我取消。所以回到解决方案 - nextInt() 调用在读取不是整数的字符串时会引发异常。你有一些选择来解决它。最简单的是使用try-catch,你可以google一下。否则你可以用 .next() 替换 .nextInt() 调用,但是你必须自己检查它是否为整数(查看stackoverflow.com/questions/5439529/…)。希望它会有所帮助
    猜你喜欢
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多