有多少人试图猜测

时间:2015-07-04 01:25:06

标签: java

我有一个彩票计划,我想请我猜一下'获胜'号码,然后会产生这些数字。完成后,它会将这些数字打印回给我,并告诉我为达到正确答案所需的尝试次数。

我的代码如下。我以为我从另一个帖子得到了答案,我确定关闭了它 - 现在找不到它。我的问题实际上只是“我的代码出了什么问题?”类型,因为我认为代码是有效的,但由于数组是6个数字,我认为这将花费一些时间。

出于这个原因,我将数组更改为只有1个数字,并且仍然需要永远回过头来回答“你猜对了......”让我相信我还有其他错误。

package lottery;

import java.util.Scanner;

public class lottery { // Begin lottery class
    public static void main(String[] args) { // Begin MAIN method

        // Define variables
        Scanner keyboard = new Scanner(System.in);
        int[] lottery = new int[6];
        int randomNum = 1 + (int) Math.random() * 59;
        int noTimes = 1;
        int guess = 0;
        // End variable definition

        System.out.println("Generating lottery numbers, what is your guess?");
        while (guess != randomNum) {
            guess = keyboard.nextInt();
            guess++;
        }

        // Input received - generate numbers now
        System.out.println("Thank you. Generating lottery numbers now...");

        for (int i = 0; i < 6; i++) {
            randomNum = (int) Math.ceil(Math.random() * 59); // Random number created here.
            for (int x = 0; x < i; x++) {
                if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
                {
                    randomNum = (int) Math.ceil(Math.random() * 59);// If random number is same, another number generated.
                    x = -1; // restart the loop
                }

            }
            lottery[i] = randomNum;
        }

        for (int j = 0; j < noTimes; j++) {
            for (int i = 0; i < lottery.length; i++) {
                System.out.print("The winning numbers are: " + lottery[i] + " ");
            }
            System.out.println("\n");
            System.out.print("You correctly guessed in " + guess + " tries.");
        }
    } // End MAIN method   
} // End Lottery class

显然,我不知道如何进行常规代码标记?颜色?

1 个答案:

答案 0 :(得分:1)

您的代码中存在各种问题,如下所述。

  1. 要生成1到59之间(但不是60)的随机整数,请在3个位置使用以下代码段:

    int randomNum = 1 + (int)(Math.random() * 59);
    
  2. 需要修复猜测逻辑(如下所述):

    int noTimes = 0;  // Corrected
    ...
    while (guess != randomNum) {
        guess = keyboard.nextInt();
        noTimes++;  // Corrected
    }
    
  3. 最后一对for循环(连续3次打印之前的那些)看起来很奇怪。这是一个更明智的替代品:

    System.out.print("The winning numbers are:");
    for (int i = 0; i < lottery.length; i++) {
        System.out.print(" " + lottery[i]);
    }
    System.out.println();
    System.out.println("You correctly guessed in " + noTimes+ " tries.");
    
  4. 除此之外,到目前为止,您的代码看起来还不错。

    PS:从59个元素中选择6个有序项目有324亿个可能性。