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 withscan.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 usebreakto exit the infinitewhile(true)loop immediately. - Error Handling: A
try-catchblock catchesNumberFormatException—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:
- 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).
- Check for the exit condition early: Place the exit check right after reading input. If it matches, use
breakto exit the loop—this is the cleanest way to terminate an infinite loop in Java. - Add flexibility (optional): Using
equalsIgnoreCaselets users enter "x" or "X" to exit, making the program more user-friendly.
内容的提问来源于stack exchange,提问作者Hrbz
相关产品推荐
相关产品推荐

