gpt4 book ai didi

java - 为什么我的代码不能多次随机生成?

转载 作者:行者123 更新时间:2023-12-02 05:03:59 25 4
gpt4 key购买 nike

抱歉,这可能是一个新手问题,但我无法弄清楚这段代码有什么问题。我到处都找过了,但找不到任何答案。

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

}
}

最佳答案

您为 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

关于java - 为什么我的代码不能多次随机生成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27975491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com