每次我运行我的程序来获得两个随机生成的整数的总和,结果总是0 + 0.请让我知道我缺少的是什么。
public void question() {
System.out.println("What is " + Random1 + "+" + Random2 + "?");
userAnswer = scan.nextInt();
System.out.println("You entered: " + userAnswer);
}
public void actualAnswer() {
Answer = (Random1 + Random2);
System.out.println("The Correct Answer is: " + Answer);
if(userAnswer==(Answer)) {
System.out.println("You answered correctly!");
}
else {
System.out.println("You answered incorrectly");
}
}
private void random1() {
Random1 = random.nextInt(10) + 1;
}
private void random2() {
Random2 = random.nextInt(10) + 1;
}
答案 0 :(得分:0)
虽然您的背景对我来说不是很清楚,但我从您的问题中理解的是,您无法为总和生成随机数。我编辑了一个零件,我的解决方案为您提供随机生成的整数的总和。希望这将是一个帮助:)
import java.util.Random;
import java.util.Scanner;
public class RandomGenerator {
int randomInt1 =0;
int randomInt2 =0;
Scanner scan=new Scanner(System.in);
int userAnswer;
int answer;
/*public void question() {
System.out.println("What is " + randomInt1 + "+" + randomInt2 + "?");
userAnswer = scan.nextInt();
System.out.println("You entered: " + userAnswer);
}*/
public void actualAnswer() {
answer = (random1() + random2());
System.out.println(" numbers generated are: "+ random1()+", "+random2());
System.out.println("The Sum is: " + answer);
/* if(userAnswer==(answer)) {
System.out.println("You answered correctly!");
}
else {
System.out.println("You answered incorrectly");
}*/
}
private int random1() {
Random randomGenerator = new Random();
for(int i =0; i<3; i++){
randomInt1 = randomGenerator.nextInt(10);
}
return randomInt1;
}
private int random2() {
Random randomGenerator = new Random();
for(int i =0; i<3; i++){
randomInt2 = randomGenerator.nextInt(10);
}
return randomInt2;
}
public static void main(String a[]){
RandomGenerator rg=new RandomGenerator();
rg.actualAnswer();
}
}