简体   繁体   English

如何使程序继续执行代码而不再次打印它

[英]How to make program continue code without printing it more then once

I have this 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);
    }
    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");
        }
    }
}
}

My problem is that my program print me three time message, if user hit lucky number program print me one message "you hit a happy number" and if user miss lucky number, program print me one message "you hit a happy number" and then twice " you did not hit a lucky number". 我的问题是我的程序向我打印了三个时间消息,如果用户打了幸运数字,程序将向我打印一条消息“您打了一个快乐数字”,而如果用户错过了幸运数字,程序将向我打印了一条消息“您打了快乐数字”,然后两次“您没有碰到幸运数字”。

So my question is how to make program that print just one message. 所以我的问题是如何使程序仅打印一条消息。

Try using break in your for loop, for the success case: 对于成功案例,请尝试在for循环中使用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");
        break; // I added this
    } else {
        JOptionPane.showMessageDialog(null, "you did not hit a lucky number");
        break;
    }
}

The break keyword is used for control flow in Java code. break关键字用于Java代码中的控制流。 In the above case, when used inside the for loop it terminates that loop, and the code continues with whatever follows immediately after the end of the loop. 在上述情况下,当在for循环内使用时for它将终止该循环,并且代码将在循环结束后立即继续执行后续操作。

break the loop as soon as luck number is hit! 一旦碰到运气数字就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;
    }

Break once as soon as you determine the hit or miss. 确定击中或未击中后立即中断。 But then you should not be looping 3 times at first place. 但是,您不应一开始就循环3次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM