如何修改Java代码使程序仅输出一次结果提示而非多次重复输出
Let's sort out this problem where your code pops up three separate messages—we want just one final result after all three tries, right?
What's Going Wrong Now
Your current loop shows a dialog every time it runs a random check. That's why you get three messages, even if you hit a lucky number on the first try. Instead, we need to track whether a hit happened at any point during the three attempts, then display one summary message at the end.
Also, heads up: Your original random number generation Math.random() * 10 creates numbers from 0 to 9, but your user is inputting values from 1-10. That means a user entering 10 will never win! I fixed that in the modified code below to match the input range.
The Solution
Here's how to adjust your code step by step:
- Add a boolean flag to keep track of whether the user hit a lucky number in any of the three tries.
- Remove the dialogs from inside the loop—only update the flag when a match is found.
- After the loop finishes, show a single dialog based on the flag's value.
Modified Code
public void checkUserLuckyNumber(PC p, User u) { int userLuckyNumber = Integer.parseInt(JOptionPane.showInputDialog(null, "Input lucky number from 1 - 10:")); if (userLuckyNumber < 1 || userLuckyNumber > 10) { JOptionPane.showMessageDialog(null, Constants.INVALIDINPUTNUMBER); System.exit(0); } // Flag to track if we hit the lucky number in any try boolean hitLuckyNumber = false; for (int i = 1; i <= 3; i++) { // Generate random number between 1-10 (matches user input range) int threeLuckyNumbers = (int) (Math.random() * 10) + 1; if (userLuckyNumber == threeLuckyNumbers) { hitLuckyNumber = true; // Optional: Add a break here to stop the loop early once a hit is found // break; } } // Show single final message if (hitLuckyNumber) { JOptionPane.showMessageDialog(null, "you hit a happy number"); } else { JOptionPane.showMessageDialog(null, "you did not hit a lucky number"); } }
Extra Tip
If you don't need to run all three tries once the user hits a lucky number, add a break; inside the if block where you set hitLuckyNumber = true. That will stop the loop early, which is a small efficiency win.
内容的提问来源于stack exchange,提问作者user10619965

