簡體   English   中英

調用靜態無效方法

[英]Calling Static Void Methods

我仍在學習使用方法,但是我遇到了另一個障礙。 我試圖在另一個靜態void方法中調用靜態void方法。 因此大致如下所示:

public static void main(String[] args) {
....
}

//Method for total amount of people on earth
//Must call plusPeople in order to add to total amount of people
 public static void thePeople (int[][] earth) {
How to call plusPeople?
}

//Method adds people to earth
//newPerson parameter value predefined in another class.
public static void plusPeople (int[][] earth, int newPerson) {
earth = [newPerson][newPerson]
}

我已經嘗試了幾種不同的方法,但實際上並沒有奏效。

int n = plusPeople(earth, newPerson); 
//Though I learned newPerson isn't recognized 
because it is in a different method.

int n = plusPeople(earth); \
//I don't really understand what the error is saying,
but I'm guessing it has to do with the comparison of these things..[]

int n = plusPeople;
//It doesn't recognize plusPeople as a method at all.

我什至無法調用方法,這讓我感到非常愚蠢,但是我已經在這個問題上停留了大約兩個小時。

如果無效,則無法將其分配給任何對象。

只需使用

int n = 5;
plusPeople(earth, n);

您遇到的第一個錯誤是因為newPerson不是在本地定義的(您是對的,它是在另一種方法中)。您遇到的第二個錯誤是因為返回類型“ void”不是“ int”。 您遇到的第三個錯誤是因為它沒有括號,並且可能認為應該有一個名為plusPeople的變量。

您需要提供兩個參數。 第一個必須是int[][]類型(並且earth符合條件),第二個必須是int類型。 因此,例如:

plusPeople(earth, 27);

當然,那只是技術上的答案。 您真正應作為參數傳遞的內容取決於該方法對其參數進行的操作(應在其javadoc中指定),參數的含義(應在其javadoc中指定)以及您希望該方法為您做什么(您應該知道)。

另外,請注意,由於該方法被聲明為void plusPeople(...) ,因此它不會返回任何內容。 所以做int n = plusPeople(earth, newPerson); 沒有任何意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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