设置我的Hangman方法并在我的main方法中调用它们

时间:2016-07-04 19:26:37

标签: java oop methods main

将我的Game类中的方法调用到我的hangman游戏的主要方法时遇到困难。 我们应该旋转一个轮子来获得100,250或500美元的累积奖金,然后按照你预期的那样玩游戏......但方法是必需的。我无处可去,我只是想在此时调用我的方法,看看它是如何工作的。 这是我的代码:

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:错误:找不到符号System.out.print(&#34;之后   转动方向盘,你得到了#34; + spinWheel()); ^

2 个答案:

答案 0 :(得分:0)

要从另一个类调用方法,您需要创建方法public。完成后,如果您将多次调用相同的方法并且希望每次执行相同的功能(参数仍然可以不同),请将它们设为static

要调用该方法,请执行以下操作(这是大多数类和方法的一般形式,您应该可以使用它来调用所有方法):

yourClassWithMethod.methodName();

答案 1 :(得分:0)

您的spinWheel方法调用中存在以下几个问题:

  1. 您尚未实例化任何任何Game对象来调用此方法。您必须将其设为static或仅实例化Game并从该对象中调用它。我个人更喜欢第二个(非静态)选项,因为,特别是因为静态方法无法直接访问非静态方法或变量(...您需要一个实例或使它们成为static)。
  2. 主要是你可以这样做(非静态解决方案):

    Game game = new Game();
    System.out.print("After spinning the wheel, you got " + game.spinWheel());
    
    1. spinWheel需要int[]类型的参数。它似乎没有用,因为有一个实例变量jackpotAmount似乎是为了这个目的而创建的。 jackpotAmount(另见第二点)在你的例子中应该是静态的。
    2. 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[]