难以将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("After旋转轮子,你得到" + spinWheel());^
要从另一个类调用方法,您需要使方法public
。一旦完成,如果您将多次调用相同的方法并且每次都希望它执行相同的功能(参数仍然可以不同),则将它们设置为static
。
要调用方法,请执行以下操作(这是大多数类和方法的通用形式,您应该能够使用它来调用所有方法):
yourClassWithMethod.methodName();
有几个问题在你的spinWheel
方法调用:
- 你还没有实例化任何
Game
对象来调用这个方法。要么你必须让它成为static
,要么只是实例化一个Game
,然后从那个对象调用它。我个人更喜欢第二种(非静态)选项,因为,特别是因为静态方法不能直接访问非静态方法或变量(…你需要一个实例或使他们(static
)。在main中,您可以这样做(非静态解决方案):
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[]