我是一名文凭学生,目前是编程和 Java 语言的新手,我正在制作一个应用程序来教授和训练 children 如何乘法。该程序生成两个随机数并将其打印在屏幕上供 children 回答。我编写的这个程序的问题是,在打印随机问题时,我的随机数似乎不起作用。程序编译成功,一切看起来都很好。但是一旦我运行它,两个随机数总是“0”。你们介意给出一些关于为什么我的随机数总是生成为“0”的指示吗?欢迎额外的批评和建议,以便改进以供将来引用:)
这是我的主要驱动程序类
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package multiplicationteacher;
import java.util.Scanner;
/**
*
* @author Jeremy Lai
*/
public class MultiplicationTeacher {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
QuestionSystem qs = new QuestionSystem();
int userInput;
System.out.println("How much is " + qs.num1 + "times" + qs.num2 + "?");
System.out.print("Enter your answer (-1 to quit) : ");
userInput = input.nextInt();
if (userInput == qs.answer(userInput)) {
System.out.print("Very Good!");
}
else {
System.out.print("No. Please try again");
}
}
}
这是我的方法类
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package multiplicationteacher;
import java.util.Random;
/**
*
* @author Jeremy Lai
*/
public class QuestionSystem {
Random rand = new Random();
public int num1;
public int num2;
public int answer;
public int randNum1(int num1) {
num1 = rand.nextInt();
return num1;
}
public int randNum2 (int num2) {
num2 = rand.nextInt();
return num2;
}
public int answer (int answer) {
answer = num1 * num2;
return answer;
}
}
提前致谢! :)
最佳答案
在您的整个代码中,您永远不会调用 randNum1
和 randNum2
方法!所以它们没有生成!
您可以使用构造函数,因此在创建 QuestionSystem
实例时调用这些值。
public QuestionSystem(){
this.randNum1();
this.randNum2();
}
此外,您的 randNum 方法中不必有任何返回值或参数:
public void randNum1() {
num1 = rand.nextInt();
}
或者,如果您只生成这些数字一次,则可以在 QuestionSystem 构造函数中包含所有内容:
public QuestionSystem(){
num1 = rand.nextInt();
num2 = rand.nextInt();
}
此外,如果这是针对 child 的,请使用 nextInt 的范围将值返回到可重新调整的大小:
num1 = rand.nextInt(100); //returns values from 0 to 99
关于Java随机数问题。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19345012/