Java 要求1到10之间的整数的递归方法
我正在尝试编写一个方法,该方法应该递归地要求用户输入一个从1到10(包括1到10)的值 这就是我所拥有的:Java 要求1到10之间的整数的递归方法,java,recursion,methods,Java,Recursion,Methods,我正在尝试编写一个方法,该方法应该递归地要求用户输入一个从1到10(包括1到10)的值 这就是我所拥有的: public static void main(String[] args) { int value = readGoodInput(); System.out.println("The user entered: " + value); } public static int readGoodInput(){ int value; Scanne
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;
}
publicstaticvoidmain(字符串[]args){
int value=readGoodInput();
System.out.println(“用户输入:“+值”);
}
公共静态int readGoodInput(){
int值;
扫描仪输入=新扫描仪(System.in);
System.out.println();
System.out.println(“输入值:”);
value=input.nextInt();
如果(值=1){
返回值;
}
否则{
readGoodInput();
}
返回值;
}
当我运行程序时:
输入一个值:
11
输入一个值:
22
输入一个值:
3
用户输入:11
我的问题是:为什么最后打印的值不是3(介于1和10之间),而是11
提前谢谢大家,
滴滴您需要返回值:
else {
return readGoodInput();
}
否则代码将被执行,但“良好输入”永远不会返回,只返回第一个。您不需要执行递归,您可以通过使用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;
}
public static int readGoodInput(){
int值=0;
扫描仪输入=新扫描仪(System.in);
而(值<1 | |值>10){
System.out.println(“输入值:”);
value=input.nextInt();
}
返回值;
}
您必须仔细遵循递归。查看递归发生的位置以及返回的值。请参阅下面的评论作为指导
在下面的递归调用中,您的第一个递归值永远不会更改。因此,第一次使用的值将是主方法中显示的值
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.
}
为什么最终的返回值是;返回第一个readGoodInput()值?将每个递归视为它自己的大小写。还要注意它的not
value=readGoodInput()如何
我以前确实被这类问题难住了。我已经调整了答案来解释你的下一个问题。这解决了OP的问题,但没有解释问题。这不是递归的适当用法。这是一门老师要求你这样做的课吗?哦,是的。。。不幸的是,为什么,为什么,为什么,为什么,为什么,为什么,为什么,为什么。。。难道教师不能想出如何在不强迫学生编写糟糕代码的情况下教授递归吗。。。
else{
value = readGoodInput(); // This is where your recursion happens.
}