You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java斐波那契序列生成器无效输入处理:无限循环问题修复求助

修复斐波那契生成器的无限循环问题

你的代码出现无限循环的核心原因是:当输入非数字内容时,Scanner.nextDouble()会抛出异常,但无效输入仍留在Scanner的输入缓冲区中,下一次循环调用nextDouble()时会直接读取到这个无效内容,再次触发异常,导致循环无法正常获取新的用户输入。

以下是基于你现有逻辑的修复方案:

修改后的完整代码

import java.util.Scanner;

public class FibonacciGenerator {
    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!");
        int number = 0;
        boolean error;

        do {
            error = false;
            try {
                System.out.println("Enter a number to use as an upper limit. The Fibonacci Sequence will be generated up to that number.");
                number = in.nextInt(); // 直接用int类型,符合正整数需求
                if (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 f0 = 0;
                    int f1 = 1;
                    int fn;
                    do {
                        System.out.print(f0 + " ");
                        fn = f0 + f1;
                        f0 = f1;
                        f1 = fn;
                    } 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;
                in.nextLine(); // 清空缓冲区的无效输入,避免无限循环
            }
        } while (number < 0 || error);
    }
}

关键修改点说明

  1. 替换数据类型:把double number改成int number,因为需求是正整数,直接用int可以省去number%1 !=0的判断,同时避免double类型的精度问题。
  2. 清空输入缓冲区:在catch块中添加in.nextLine(),将残留的无效输入(比如用户输入的字符串、空格等)从缓冲区中清除,确保下一次循环能正常读取新的用户输入。
  3. 简化循环条件:移除number%1 !=0的判断,因为现在用int类型,天然保证是整数,循环条件只需要判断number <0或error即可。

内容的提问来源于stack exchange,提问作者RileyGT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 08:52:18