2014-11-01 96 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