簡體   English   中英

Java 將數組傳遞給另一個 class 中的方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM