繁体   English   中英

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

[英]Why isn't my code randomly generating more than once?

很抱歉,这个问题可能有点令人讨厌,但是我无法弄清楚这段代码有什么问题。 我到处都看过,但找不到任何答案。

问题是,当我需要随机生成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!");
                }

    }
}

num2一次为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

在这种情况下,当您调用nextNum()时,您将生成一个随机数。您可以看到,由于num和num2不在循环中,因此只能对其调用一次。

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

暂无
暂无

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

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