Java:两位数的彩票

时间:2015-03-17 17:23:30

标签: java

我正在研究这个彩票代码,但经历了无休止的运行。我希望指出代码可能有什么问题,以及如何纠正它。谢谢。问题是“生成一个两位数的抽奖。数字中的两个数字是不同的。(提示:生成第一个数字。使用循环连续生成第二个数字,直到它与第一个数字不同。)

public class Lottery1 {

    public static void main(String[] args) {
        // Create  Scanner
        Scanner s = new Scanner(System.in);
        //generate 2 digit random  lottery  number
        int lottery = (int) (Math.random() * 100);
        // TODO code application logic here
        //generate first and second digit of lottery
        int lotterydigit1 = lottery / 10;
        int lotterydigit2 = lottery % 10;
        while (lotterydigit2 != lotterydigit1) {
            lotterydigit2 = lottery % 10;
        }

        //prompt user for guess digits 
        System.out.print("Enter two Digit  number:");
        int guess = s.nextInt();
        int guessdigit1 = guess / 10;
        int guessdigit2 = guess % 10;

        // compare lottery and 
        if (guessdigit1 == lotterydigit1 && guessdigit2 == lotterydigit2) {
            System.out.println("You  just won $10,0000");
        } else if (guessdigit1 == lotterydigit2 && guessdigit2 == lotterydigit1) {
            System.out.println("You  have  won $5,000");
        } else if (guessdigit1 == lotterydigit1
                || guessdigit1 == lotterydigit2
                || guessdigit2 == lotterydigit1
                || guessdigit2 == lotterydigit2) {
            System.out.println("You have won $1,000");
        } else {
            System.out.println("You  have  not won anything");
        }
        System.out.println("lottery number is" + " " + lottery + " and     your  guess is" + guess);
    }

}

3 个答案:

答案 0 :(得分:0)

你希望它们不同,所以改变

   while (lotterydigit2!=lotterydigit1){
              lotterydigit2 = lottery%10;
                }

while (lotterydigit2==lotterydigit1){
          lotterydigit2 = lottery%10;
            }

答案 1 :(得分:0)

while (lotterydigit2!=lotterydigit1){
      lotterydigit2 = lottery%10;
}

lotterydigit2始终具有相同的值。如果第一次运行中彩票%10是!= lotterydigit1,它将不会退出循环,因为你没有改变任何东西。

答案 2 :(得分:0)

您的问题的答案在于您的提示:

  

使用循环连续生成第二个数字,直到它与第一个数字不同。

你在循环中没有生成任何东西:

while (lotterydigit2 != lotterydigit1) {
    lotterydigit2 = lottery % 10;
}

你也有错误的条件 - “直到它不同”意味着“虽然它们是相同的”。

我建议分别生成两位数字:

int lotterydigit1 = (int) (Math.random() * 10);
int lotterydigit2 = (int) (Math.random() * 10);
while (lotterydigit2 == lotterydigit1) {
    lotterydigit2 = (int) (Math.random() * 10);
}