java - 运行此程序时出现错误
问题描述
这是我的代码:
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
解决方案
使固定:
您添加了“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]);
}
}
}
推荐阅读
- node.js - openssh 使用加密生成的密钥对返回“错误的密钥类型”
- java - 我们可以跳过 testng xml 中的 java @AfterClass 方法吗
- vba - 公用函数的 SQL 语句
- google-apps-script - Apps 脚本在每个新行上触发 API 调用
- kubernetes - 我应该更喜欢 Kustomize 而不是 Helm
- bash - Pfsense 2.4.4:自定义脚本运行到 Crontab 以执行 CURL http-response status 问题
- phpunit - PHPUnit - 为 foreach() 提供的无效参数无法识别,尽管期待它
- rest - REST API cURL 令牌 - Paylocity
- c - 共享内存不更新
- python - Pytorch - 如何提取 MLP 网络的特征(权重、偏差、节点数、隐藏层)?