为什么我的代码不会随机生成多次?

时间:2015-01-16 00:31:19

标签: java

很抱歉这可能是一个愚蠢的问题,但我无法弄清楚这段代码有什么问题。我到处都看,但我找不到任何答案。

问题是,当我需要随机生成5次时,它只会随机生成一次num和num2。非常感谢任何帮助。

import java.util.Scanner;

import java.util.Random;

public class Choice5
{
    public static void main(String [] args)
    {
        Random r = new Random();
        Scanner k = new Scanner(System.in);
        String name;

        int num= 1 + r.nextInt(10);
        int num2=1 + r.nextInt(10);

        int answer = num*num2;
        int attempt;
        int countcorrect = 0;
        int countincorrect =0;

        System.out.println("Hi, what's your name?");
        name =k.next();

        for(int x=1; x<=5; x++)
        {
            System.out.println("Test " +x+ " of 5");
                System.out.println("Ok " +name+ " What is " +num+ " x " +num2+ " ?");
                attempt = k.nextInt();

                if(attempt == answer)
                {
                    System.out.println("Good Job " +name+ " the answer was indeed " +answer);
                    countcorrect++;
                }
                if(attempt != answer)
                {
                    System.out.println("Incorrect " +name+ " the answer was actually " +answer);
                    countincorrect++;
                }
        }
                System.out.println("You got " +countcorrect+ " right");
                System.out.println("You got " +countincorrect+ " wrong");
                if (countcorrect < 3)
                {
                    System.out.println("You should try the test again");
                }
                else
                {
                    System.out.println("Good job " +name+ " ,you passed the test!");
                }

    }
}

2 个答案:

答案 0 :(得分:2)

您选择numnum2的随机数一次,位于main的顶部,更重要的是,在for循环之前。这些数字不会再次分配,因此在所有循环迭代期间它们保持不变。

要让它们针对每个循环迭代进行更改,请声明数字和答案的变量,并在for循环内而不是之前分配新值。

for(int x=1; x<=5; x++)
{
    int num= 1 + r.nextInt(10);
    int num2=1 + r.nextInt(10);
    int answer = num*num2;
    // rest of code is the same

答案 1 :(得分:0)

你生成一个随机数,在这种情况下,你调用nextNum()正如你所看到的那样,你只为num和num2调用一次,因为它不在循环中。

简单的回答,将这些调用放在你的循环中以创建多个随机数。