首页 > 解决方案 > 运行此程序时出现错误

问题描述

这是我的代码:

import java.util.Random;

public class Arrayss3 {

    public static void printArray(double a[]) {
        for(int i=0;i<a.length;i++) {
            System.out.println(a[i]);
        }
    }

    public static void main(String args[]) {
        Random gen=new Random();
        double [] a=new double[10];
        Arrayss3 ar=new Arrayss3();

        for(int i=0;i<a.length;i++) {
            a[i]=gen.nextInt(141)+60;
            System.out.println(printArray(a[i]));
        }
    }

}

这是我运行它时给我的错误:

Arrayss3.java:20: error: incompatible types: double cannot be converted to double[]
System.out.println(printArray(a[i]));
                               ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

标签: java

解决方案


使固定:

您添加了“double a[]”作为 printArray 的参数,而您仅将其用作“double”。

建议:

  • 我建议您使用 Random gen = new Random(); 在您的主要方法之外,以防您想在任何其他方法中再次使用它,以获得更好的性能,例如降低使用的内存。确保将其设为静态。

  • 您使用了 Arrayss3 ar = new Arrayss3(); 当您已经在 Arrayss3 课程中时。只需使用 printArray 而不需要这个对象。

  • 您正在打印一个不返回任何内容的方法。如果您希望此方法返回,请使用类似的内容:

    static Random gen = new Random();
    
    public static void main(String[] args) {
        double[] a = new double[10];
        for (int i = 0; i < a.length; i++) {
            a[i] = gen.nextInt(141) + 60;
        }
        for (Double value : printArray(a)) {
            System.out.println(value);
        }
    }
    
    public static ArrayList<Double> printArray(double a[]) {
        ArrayList<Double> arrayList = new ArrayList<Double>();
        for (int i = 0; i < a.length; i++) {
            arrayList.add(a[i]);
        }
        return arrayList;
    }
    

    }

最终代码:

你需要使用这样的东西才能让它工作。

import java.util.Random;

public class Arrayss3 {
    static Random gen = new Random();

    public static void main(String[] args) {
        double[] a = new double[10];
        for (int i = 0; i < a.length; i++) {
            a[i] = gen.nextInt(141) + 60;
        }
        printArray(a);
    }

    public static void printArray(double a[]) {
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}

推荐阅读