2014-11-01 92 views
0

所以我試圖調用一個方法displayBoard在java中顯示一次用戶輸入一個數字,最初在主要方法中的桌面遊戲。我無法調用這個方法。有沒有人看到我要去哪裏錯了,或者我該如何解決這個問題?謝謝。方法調用問題Java

public static void displayBoard(int [] board, boolean showItem) 
{ 
    System.out.println(); 
    System.out.print("_"); 
    for (int val : board){ 
     switch(codes){ 
     case 2: 
     System.out.print("x"); 
     break; 
     case 3: 
     System.out.print(" "); 
     break; 
     case 4: 
     System.out.print(showItem ? "Y" : " "); 
     break; 
    } 
    System.out.print("_"); 
} //for 
System.out.println(); 
System.out.println(); 
}//display 

public static void main (String [] args) 
{ 
    int guess = 0; 
    int userInput = promptForInt("Length Of board"); 
    int [] numbers = new int[userInput]; 
    int randomlocs = new Random().nextInt(userInput); 
    int val; 
    int display = displayBoard(board [], boolean showItem) // doesnt work? 
    boolean showItem = false; 


    while(! showItem) 
    { 
     val = promptForInt("Try Again!"); 
     if(guess == randomlocation) 
     { 
      System.out.println("Found it!"); 
      showItem = true; 
     } 
     else if(guess != randomlocs) 
     System.out.print(val); 
    } 
} 

回答

1

問題

您必須將值傳遞給方法調用。現在,你是路過聲明的方法,這是不正確的Java語法

如何修復

首先,聲明你showItem布爾調用方法之前,讓你有一個boolean到傳遞給方法。它應該是這樣的:

boolean showItem = false; 
int display = displayBoard(numbers, showItem) 

這會通過存儲在您的numbersshowItem變量vakues。我們知道存儲在這些特定變量(numbersshowItem)中的值應該由於方法的參數名稱而被傳入。

導致這一方法調用看起來應該像這樣的語句:

int userInput = promptForInt("Length Of board"); 
int [] numbers = new int[userInput]; 
boolean showItem = false; 
int display = displayBoard(board [], boolean showItem); 

int randomlocs = new Random().nextInt(userInput); //since this isn't used before the method call, it should be declared below it 
int guess = 0; //same with this 
int val; //and this 
+0

謝謝您的回答,我明白的地方我現在去錯了。目前我正在嘗試此操作,並說「不兼容類型」。 – Zinconium 2014-11-01 07:17:27

+1

@Zynk這是因爲'displayBoard'是一個'void'方法,它不返回一個值。它應該是一個'int'方法,它返回一個整數,或者你不應該用它初始化一個變量,就像你使用'int display = displayBoard(int [],boolean)''一樣。我看到它的方式,你不需要'int display'變量 – 2014-11-01 07:20:44

+0

啊我看到了,它看起來不像我需要它,但是當我運行執行程序時,當用戶升級爲在promptForInt中的一個值,這就是爲什麼我認爲我需要它。 謝謝你的幫助! :) – Zinconium 2014-11-01 07:25:11