我试图制作一个刽子手程序并且我没有错误,但程序将在我运行时终止。你看到我的代码有什么问题吗?我可以将StringBuilder添加到我的代码中更改的字符串吗? 我还想创建一个驱动程序类,但不确定要放入什么。
package hangman;
import java.util.Random;
public class hangman
{
public static void main1(String[] args){
}
//the word to be guessed
private String word = null;
// the array of possible words */
private String[] wordArray = {"help","word","work","pant", "farm", "blue", "swim", "bike", "jump", "snow"};
// the random number generator */
private Random randNumGen = new Random();
// the characters that were guessed that were wrong */
private String wrongGuesses = "";
// the characters that were guessed that were right */
private char[] rightGuesses = {' ',' ',' ', ' '};
// Randomly picks the word from the wordArray
public hangman()
{
int index = randNumGen.nextInt(wordArray.length);
word = wordArray[index];
}
public boolean guess()
{
boolean done = false;
Object SimpleInput;
// get input from user
String guessStr = ("Enter a letter");
// check if still have at least one letter
if (guessStr.length() > 0)
{
// get first letter
char guessChar = guessStr.charAt(0);
// check this letter
done = this.guess(guessChar);
}
return done;
}
//Method to guess a letter
public boolean guess(char guessChar)
{
int index = word.indexOf(guessChar);
boolean done = false;
// if the letter is in the word
if (index >= 0)
{
// add letter to correctly guessed letters
rightGuesses[index] = guessChar;
// check if the user won
int numRightGuesses = 0;
if (numRightGuesses == 4)
{
done = true;
}
}
else
{
// add letter to string with wrong letters
wrongGuesses = wrongGuesses + guessChar + " ";
int numWrongGuesses = 0;
// check if this was the last wrong guess
if (numWrongGuesses == 6)
{
done = true;
}
}
return done;
}
/**
* Method to play the game till the user
* wins or loses
*/
public void playGame()
{
boolean done = false;
// loop while we haven't reached the end of the game
while (!(done = guess()))
{}
}
}
答案 0 :(得分:1)
您的程序需要一个起始点。 计算机需要知道程序的开始位置。
开头的public static void main(String[] args)
方法在“主”之后落后于“1”,即一个点。
另一点是你必须用main方法调用你的游戏。
public static void main(String[] args) {
hangman game = new hangman();
game.playGame();
}
答案 1 :(得分:0)
您的main()方法为空。这是您的应用程序的主要入口点,它没有做任何事情,所以程序干净利落。成功...?
答案 2 :(得分:0)
使用以下代码替换main方法,它将创建类的对象,并且将执行构造函数内的代码
public static void main(String[] args){
hangman game = new hangman();
game.PlayGame();
}