【问题标题】:java error: double cannot be dereferencedjava错误:无法取消引用双精度
【发布时间】:2016-02-21 10:32:53
【问题描述】:

好的,所以我需要生成 7 个介于 1 和 100 之间的随机数,并将最大值打印在屏幕上。但是,当我编译这段代码时:

public class ArrayofTemperatures
{
   public static void main(String[] args)
   {

      double [] temp = new double [7];
      int index;
      double max;
      double random = Math.random() * 100 + 1;

      temp[0] = random.nextDouble();
      max = temp[0];
      for (index = 1; index < temp.length; index++)
      {
         temp[index] = random.nextDouble();
         if (temp[index] > max)
            max = temp[index];

      }

      System.out.println("The highest score is: " + max);
   }
}

我得到这两个错误:

ArrayofTemperatures.java:12:错误:无法取消引用双精度 temp[0] = random.nextDouble();

ArrayofTemperatures.java:16:错误:无法取消引用双精度 temp[index] = random.nextDouble();

【问题讨论】:

    标签: java arrays random numbers


    【解决方案1】:

    你弄糊涂了。

    此语句产生一个 double 值:

    double random = Math.random() * 100 + 1;
    

    如果你想要一个随机生成器,请使用

    Random random = new Random ();
    

    那么random.nextDouble() 将产生一个介于 0.0 和 1.0 之间的数字。

    另一种方法是将调用random.nextDouble() 替换为Math.random()

    【讨论】:

    • 好的,谢谢!我摆脱了错误,但是就像你说的那样,这个数字只会在 0.0 到 1.0 之间产生。如果您不介意回答另一个问题,我如何获得 1 到 100 之间的数字
    • @ValRadcliffe 您可以编写一个返回Math.random() * 100 + 1random.nextDouble() * 100 + 1 的方法(取决于您希望使用静态Math.random() 方法还是Random 类的实例方法)。
    • 再次感谢您!我正在学习初学者级别的 Java 课程,有时它非常难!
    【解决方案2】:

    random 是基本类型double,因此没有方法,也没有nextDouble

    我假设你想使用 Random 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多