如何让 java 的随机生成器在构造函数语句中为变量生成双精度值?
How can I get java's random generator to produce a double for variable in a constructor statement?
前言:我是新手。
这是无法编译的源代码文件,因为我收到 "method next double in class Random cannot be applied to given types."
的错误消息
import java.util.Random;
public class Student
{
private String name;
private String address;
private String major;
private double GPA;
Random generator = new Random();
public Student (String studName, String studAddr, String studMaj)
{
name = studName;
address = studAddr;
major = studMaj;
GPA = generator.nextDouble(.5, 4.0);
}
public Student (String studName, String studAddr)
{
name = studName;
address = studAddr;
major = "undeclared";
GPA = generator.nextDouble(.5, 4.0);
}
方法java.util.Random.nextDouble() 不带参数
所以将其更改为
GPA = generator.nextDouble()
LInk 到文档 http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
正如 Paul John 所说,Random.nextDouble() 不接受任何参数。对于您要尝试执行的操作,您需要如下所示的代码:
GPA = 3.5*generator.nextDouble()+0.5;
这将为您提供一个介于 0.5 和 4.0 之间的随机双精度数,因为 nextDouble() returns 一个介于 0.0 和 1.0 之间的随机值。
前言:我是新手。 这是无法编译的源代码文件,因为我收到 "method next double in class Random cannot be applied to given types."
的错误消息import java.util.Random;
public class Student
{
private String name;
private String address;
private String major;
private double GPA;
Random generator = new Random();
public Student (String studName, String studAddr, String studMaj)
{
name = studName;
address = studAddr;
major = studMaj;
GPA = generator.nextDouble(.5, 4.0);
}
public Student (String studName, String studAddr)
{
name = studName;
address = studAddr;
major = "undeclared";
GPA = generator.nextDouble(.5, 4.0);
}
方法java.util.Random.nextDouble() 不带参数 所以将其更改为
GPA = generator.nextDouble()
LInk 到文档 http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
正如 Paul John 所说,Random.nextDouble() 不接受任何参数。对于您要尝试执行的操作,您需要如下所示的代码:
GPA = 3.5*generator.nextDouble()+0.5;
这将为您提供一个介于 0.5 和 4.0 之间的随机双精度数,因为 nextDouble() returns 一个介于 0.0 和 1.0 之间的随机值。