我正在尝试创建一个斐波那契数列生成器,其中所有无效输入案例在要求用户重试之前都会有响应。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("The Fibonacci Sequence is the series of whole positive numbers where the next number is found by adding up the two numbers before it. \nGive it a try!");
double number = 0; //
boolean error;
do {
try {
error = false;
System.out.println("Enter a number to use as an upper limit. The Fibonacci Sequence will be generated up to that number.");
number = in.nextDouble();
if (number % 1 != 0 || number < 0) {
System.err.println("The Fibonacci Sequence only works with positive whole numbers, please enter a positive integer.");
} else {
System.out.println("The Fibonacci Sequence is: ");
int i = 0;
int f0 = 0;
int f1 = 1;
int fn;
double value = 0; // changed this to double which is redundant since value is not used
do {
fn = f0 + f1;
System.out.print(f0 + " ");
f0 = f1;
f1 = fn;
value = number - f0;
i++;
} while (f0 <= number);
}
} catch (Exception e) {
System.out.println("The Fibonacci Sequence only works with positive whole numbers, please enter a positive integer.");
error = true;
}
}
while (number < 0 || number % 1 != 0 || error) ;
}
但是,当我在 do-while 循环中使用 try/catch 时,我会在 catch 和输入提示中得到消息的无限循环。
斐波那契数列仅适用于正整数,请输入正整数。 输入一个数字作为上限。将生成最多该数字的斐波那契数列........
我在Java方面还不是很先进,所以现在我想找到一个使用这个逻辑的解决方案,只是找到一种方法来修复我的代码。谢谢!
它适用于任何情况,除非您输入非数字。它会循环,因为输入缓冲区中仍然有一个值,因此错误不断重复。因此,您需要删除 catch 块中的输入,如下所示:
catch (Exception e) {
System.out.println("The Fibonacci Sequence only works with positive whole numbers, please enter a positive integer.");
error = true;
in.nextLine(); // <-- Remove problem input
}
顺便说一句,既然你只需要正整数,为什么你会提示双打呢?您可能想做:
int number;
// then later
number = in.nextInt();