gpt4 book ai didi

java - 要求用户在JAVA中递归输入特定范围之间的值?

转载 作者:行者123 更新时间:2023-12-02 00:10:20 25 4
gpt4 key购买 nike

我正在用Java编写一段代码,系统会要求用户输入1到10之间的整数(包括两者),如果该值超出范围,它应该递归地要求用户再次输入值。最后我必须打印该范围内的值。下面是我的代码:

`导入java.util.Scanner;公共(public)类输入整数{

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter first Integer between 1 and 10 (both inclusive):");
Scanner sc = new Scanner(System.in);
int num1 = isInRange(sc, sc.nextInt());

System.out.println("Enter Second Integer between 1 and 10 (both inclusive):");
int num2 = isInRange(sc, sc.nextInt());

System.out.println("Num 1 is "+num1+"\nNum 2 is "+num2);
sc.close();
}

public static int isInRange(Scanner scanner, int num) {
if(num<1 || num>10) {
System.out.println("WRONG INPUT. PLease enter Integer between 1 and 10 (both inclusive):");
num =scanner.nextInt();
isInRange(scanner, num);

}
return num;
}

}`

这将是我的输出: Output Image

我面临的问题是,当我输入错误的值并且最终当我输入正确的值时,它会打印我第二次输入的值。假设我输入了 8 个超出范围的值,之后我的第 9 个值在范围内,因此它将打印第二次输入的值。

最佳答案

您错过了一些细节:

public static int isInRange(Scanner scanner, int num) {
if(num<1 || num>10) {
System.out.println("WRONG INPUT. PLease enter Integer between 1 and 10 (both inclusive):");
num = scanner.nextInt();
num = isInRange(scanner, num); // add "num = " at the beginning of the line
}
return num;
}

isInRange() 返回一个您忘记设置为 num 的整数。

关于java - 要求用户在JAVA中递归输入特定范围之间的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58125961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com