![](/img/trans.png)
[英]Which statement in my main method is calling all my other methods in my other classes and my main class?
[英]Setting up my Hangman methods and calling them in my main method
在将我的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(“旋转轮子后,您得到了” + spinWheel()); ^
要从另一个类调用方法,您需要将该方法public
。 一旦做到这一点,让他们static
,如果你将调用相同的方法很多次,你想让它每次(参数仍然可以是不同的)做同样的功能。
要调用该方法,请执行以下操作(这是大多数类和方法的通用形式,您应该可以使用此方法来调用所有方法):
yourClassWithMethod.methodName();
spinWheel
方法调用中存在几个问题:
Game
对象来调用此方法。 您必须使其为static
或者只是实例化一个Game
并从该对象调用它。 我个人更喜欢第二个(非静态)选项,因为特别是因为静态方法无法直接访问非静态方法或变量(...,您需要一个实例或将它们设置为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[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.