我有此代码:
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);
}
for (int i = 1; i <= 3; i++) {
int threeLuckyNumbers = (int) (Math.random() * 10);
if (userLuckyNumber == threeLuckyNumbers) {
JOptionPane.showMessageDialog(null, "you hit a happy number");
} else {
JOptionPane.showMessageDialog(null, "you did not hit a lucky number");
}
}
}
}
我的问题是我的程序向我打印了三条消息,如果用户打了幸运数字,程序会向我打印一条消息“你打了一个快乐数字”,而如果用户错过了幸运数字,则程序向我打印了一条消息,“你打了一个快乐数字”然后再两次“您没有碰到幸运数字”。
所以我的问题是如何制作仅打印一条消息的程序。
答案 0 :(得分:0)
针对成功案例,请尝试在break
循环中使用for
:
for (int i = 1; i <= 3; i++) {
int threeLuckyNumbers = (int) (Math.random() * 10);
if (userLuckyNumber == threeLuckyNumbers) {
JOptionPane.showMessageDialog(null, "you hit a happy number");
break; // I added this
} else {
JOptionPane.showMessageDialog(null, "you did not hit a lucky number");
break;
}
}
break
关键字用于Java代码中的控制流。在上述情况下,在for
循环中使用时,它将终止该循环,并且代码将在循环结束后立即继续执行后续操作。
答案 1 :(得分:0)
break
一旦碰到运气数字就会循环!
for (int i = 1; i <= 3; i++) {
int threeLuckyNumbers = (int)(Math.random() * 10);
if (userLuckyNumber == threeLuckyNumbers) {
JOptionPane.showMessageDialog(null, "you hit a happy number");
} else {
JOptionPane.showMessageDialog(null, "you did not hit a lucky number");
}
break;
}
确定击中或未击中后立即中断。 但是,那么您不应该一开始就循环3次。