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

Java FizzBuzz小游戏:实现输入字符X终止while(true)循环的解决方案

Got it, let's refine your FizzBuzz game to support the exit functionality with the character "X" while making it more robust. Here's the full modified code and a detailed breakdown:

Modified Complete Code
import java.util.Scanner;

public class CLass {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (true) {
            System.out.print("number: ");
            String input = scan.nextLine().trim();
            // Check for exit command, case-insensitive
            if (input.equalsIgnoreCase("X")) {
                System.out.println("goodbye");
                break; // Terminate the infinite loop
            }
            try {
                int number = Integer.parseInt(input);
                if (number % 5 == 0 && number % 3 == 0)
                    System.out.println("FizzBuzz");
                else if (number % 5 == 0)
                    System.out.println("Fizz");
                else if (number % 3 == 0)
                    System.out.println("Buzz");
                else
                    System.out.println(number);
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字或X以退出");
            }
        }
        scan.close(); // Release scanner resource
    }
}
Code Logic Explanation
  • Input Handling Overhaul: Instead of using scan.nextInt() (which throws an exception if non-numeric input is entered), we read the input as a string with scan.nextLine().trim(). This lets us check for the exit command first before trying to parse a number.
  • Exit Logic Implementation: We use equalsIgnoreCase("X") to check if the user entered "X" (or "x" for flexibility). When this condition is met, we print "goodbye" and use break to exit the infinite while(true) loop immediately.
  • Error Handling: A try-catch block catches NumberFormatException—this triggers when the input is neither a valid number nor "X". We show a friendly prompt to guide the user.
  • Resource Management: After the loop ends, we call scan.close() to properly release the scanner resource, which is good practice for handling I/O objects.
How to Terminate an Infinite Loop with a Specific Character

The key steps to make this work are:

  1. Read input as a string first: This allows us to check for the exit character before attempting to parse numeric values (avoids runtime exceptions from mismatched input types).
  2. Check for the exit condition early: Place the exit check right after reading input. If it matches, use break to exit the loop—this is the cleanest way to terminate an infinite loop in Java.
  3. Add flexibility (optional): Using equalsIgnoreCase lets users enter "x" or "X" to exit, making the program more user-friendly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:22:42