[英]Java Pass array to a method in another class
package arrays2;
public class GebruikGetallenRij {
public static void main(String[] args) {
int aantal = 5;
GetallenRij gr1 = new GetallenRij(aantal);
GetallenRij gr2 = new GetallenRij(aantal);
System.out.println("Geef " + aantal + " getallen in: ");
gr1.leesRij();
System.out.println("Geef " + aantal + " getallen in: ");
gr2.leesRij();
boolean controle = gr1.vergelijk(gr2);
if (controle) System.out.println("De 2 rijen zijn gelijk");
else System.out.println("De 2 rijen zijn NIET gelijk");
}
}
其他 class
package arrays2;
import java.util.Scanner;
public class GetallenRij {
private int [] rij;
public GetallenRij (int grootte) {
rij = new int [grootte];
}
public void leesRij() {
Scanner sc = new Scanner(System.in);
for (int i = 0; i < rij.length;i++) {
rij[i] = sc.nextInt();
}
}
public boolean vergelijk(int [] rijB) {
boolean vgl = true;
if (rij.length != rijB.length) {
return false;
}
else {
int i = 0;
while (i < rij.length && vgl) {
if(rij[i] != rijB[i]) vgl = false;
i++;
}
}
if (vgl) return true;
else return false;
}
}
该程序的想法是创建 2 个数组对象,写入值并比较它们。 但是我不能将第二个数组 gr2 传递给比较 arrays 的方法(公共 boolean vergelijk(int [] rijB)。我收到以下错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method vergelijk() in the type GetallenRij is not applicable for the arguments (GetallenRij) at arrays2.GebruikGetallenRij.main(GebruikGetallenRij.java:18)
我该如何解决这个错误?
您正在尝试将GetallenRij
object 传递给需要int[]
的方法,这会导致编译错误。
更改方法以接受GetallenRij
并将其rij
分配给局部变量int [] rijB
,使代码的 rest 保持原样:
public boolean vergelijk(GetallenRij getallenRij) {
int [] rijB = getallenRij.rij;
// rest of code same as before
}
当你在那里时,改变:
if (vgl) return true;
else return false;
至:
return vgl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.