2016-07-04 73 views
0

難以將我的Game類中的方法調用到我的Hangman遊戲的主要方法中。 我們應該旋轉輪盤才能獲得100,250或500美元的大獎,然後按照您的預期玩遊戲......但方法是必需的。我什麼都沒有接近完成我只是想在這一點上能夠調用我的方法來看看它的工作方式。 這裏是我的代碼:設置我的Hangman方法並在我的主要方法中調用它們

import java.util.Scanner; 
import java.util.Random; 

public class GameDemo { 
    public static void main(String[] args) { 
     String[] songs = {"asdnj", "satisfaction", "mr jones", 
     "uptown funk"}; //note this is a very short list as an example 
     Random rand = new Random(); 
     int i = rand.nextInt(songs.length); 
     String secretword = songs[i]; 
     System.out.print("Welcome to The Guessing Game. The topic is song  titles. \nYou have 6 guesses. Your puzzle has the following letters: "); 
     System.out.print("After spinning the wheel, you got " + spinWheel()); 

     //continue the code here. 
    } 
} 

class Game { 
    Random rand = new Random(); 
    String[] songs = {"asdnj", "satisfaction", "mr jones", 
    "uptown funk"}; 
    int i = rand.nextInt(songs.length); 
    private String secretword = songs[i]; 
    private char [] charSongs = secretword.toCharArray(); 
    private char [] guessed = new char [charSongs.length]; 
    private int guesses; 
    private int misses; 
    private char letter; 
    private char [] jackpotAmount = {100,250,500}; 

    public Game(){} 

    public int spinWheel(int[] jackpotAmount){ 
     int rand = new Random().nextInt(jackpotAmount.length); 
     return jackpotAmount[rand]; 
    } 

    public char guessLetter(char charSongs [], char letter){ 
     int timesFound = 0; 
     for (int i = 0; i < charSongs.length; i++){ 
      if (charSongs[i] == letter){ 
      timesFound++; 
      guessed[i] = letter; 
      } 
     } 
     return letter; 
    } 
} 

而返回錯誤是

GameDemo.java:11: error: cannot find symbol System.out.print("After spinning the wheel, you got " + spinWheel()); ^

+0

,你的問題是......? –

+0

對不起。當我調用spinWheel方法時,我的主要方法中有錯誤。不知道我做錯了 – Pizaz

+0

和那些錯誤是...? –

回答

0

撥叫您需要的方法public另一個類的方法。一旦完成,如果您將多次調用相同的方法並且您希望它每次都執行相同的功能(參數仍可能不同),請將它們設爲static

要調用的方法做以下(這是大多數類和方法的一般形式,你應該能夠使用所有的方法調用):

yourClassWithMethod.methodName(); 
0

有幾個問題你spinWheel方法調用:

  1. 您還沒有任何實例任何Game對象調用此方法。要麼你必須讓它static或只是實例化一個Game並從該objet中調用它。我個人更喜歡第二個(非靜態)選項,因爲特別是因爲靜態方法不能直接訪問非靜態方法或變量(...您需要一個實例或使它們成爲static)。

在主,可以做到這一點(非靜態溶液):

Game game = new Game(); 
System.out.print("After spinning the wheel, you got " + game.spinWheel()); 
  • spinWheel需要int[]類型的參數。它似乎沒有用,因爲有一個實例變量jackpotAmount似乎是爲此目的而創建的。 jackpotAmount(另見第二點)在你的例子中應該是靜態的。
  • spinWheel變爲:

    //you can have "public static int spinWheel(){" 
    //if you chose the static solution 
    //Note that jackpotAmount should also be static in that case 
    public int spinWheel(){ 
        int rand = new Random().nextInt(jackpotAmount.length); 
        return jackpotAmount[rand]; 
    } 
    

    注意jackpotAmount最好是一個int[]char[]

    相關問題