Hangman代码卡在三个不同的问题上

时间:2015-12-07 00:16:17

标签: java arrays stream

我正在尝试制作一个刽子手游戏。在每个回合,用户猜一个字母。如果他们猜对了,他们可以再次猜测。否则,他们剩余的可用猜测会逐一减少,并且猜到的字母会被放入一个数组中。

当用户点击零剩余猜测时,该程序应该询问他们是否想再次玩。如果他们回答是,则应该重新启动游戏,如果他们回答否,则程序结束。

我遇到的问题是持有猜测的数组,以及重启游戏。

此外,程序在启动时会偶尔出错。错误是

  

Hangman1.main中的线程“main”java.lang.NullPointerException中的异常(Hangman1.java:27)

尝试重新启动游戏时的错误是

  

Hangman1.main中的线程“main”java.lang.NullPointerException中的异常(Hangman1.java:101)

searchArray是应该采用char数组的位置并将其复制到星号数组并返回星号数组的方法,这似乎不起作用。运行调试似乎导致程序崩溃的问题是该单词有时会以null结尾,但有时只是我不知道为什么

import java.util.*;
import java.io.*;

public class Hangman1 {

    static Scanner keyboard = new Scanner(System.in);
    public static final int MAXSIZE = 15000;
    public static final int NUM_GUESS = 8;
    public static final int WORD_LENGTH = 20;

    public static void main(String[] args) {
        int random = pickrandom(MAXSIZE); 

        try {
            // Set up connection to the input file
            Scanner input = new Scanner(new FileReader("dictionary.txt"));

            instructions();
            keyboard.nextLine(); 
            clearScreen();

            String word = randomWord(input, random);

            System.out.println(word);
            String[] charArray = word.split("");

            System.out.print("\n");
            String[] asterisk = asteriskLine(word);

            String decision = "Y"; 
            //decision = keyboard.nextLine().toUpperCase();

            System.out.println("Word to guess :");
            for (int count = 0; count < word.length(); count++) { 
                System.out.print(asterisk[count]); 
            }
            System.out.print("\n");

            int tries = NUM_GUESS; 

            System.out.println("Enter a letter to guess or 9 to quit");
            String guess = keyboard.next();
            String[] wrongGuesses = new String [NUM_GUESS];

            int guessMade = 0;
            do {
                //System.out.println(tries); 
                while (!(guess.equals("9")) && !(guess.equals(word))  && (tries > 0))
                {
                    String letter = guess.substring(0,1); 

                    if (word.indexOf(letter) < 0) {
                        clearScreen();

                        tries--;

                        wrongGuesses = wrongGuesses(guessMade, wrongGuesses, letter);

                        printArray(asterisk, charArray, word, tries, wrongGuesses, guessMade);
                        guessMade++;
                        guess = keyboard.next();
                    }
                    else {  
                        clearScreen();
                        asterisk = searchArray(charArray, asterisk, guessMade, letter, word);
                        printArray(asterisk, charArray, word, tries, wrongGuesses, guessMade); 
                        guess = keyboard.next();
                    }

                    if (charArray == asterisk) {
                        System.out.println("You won!");
                    }

                    if (tries == 0) {
                        System.out.println("You have no more guesses left"); 
                    }

                }
                if (guess.equals("9")) {
                    System.out.println("Thanks for playing");
                }

                System.out.println("Play again? Y/N");

                decision = keyboard.next().toUpperCase();
                if (decision.equals("Y")) {
                    random = pickrandom(MAXSIZE);
                    word = randomWord(input, random);
                    charArray = word.split("");

                    System.out.print("\n");
                    asterisk = asteriskLine(word);
                    guess = keyboard.next();
                }


            } while (decision.equals("Y"));
            //System.out.println("Play again? Y/N");
            //decision = keyboard.nextLine().toUpperCase();
        }

        catch (FileNotFoundException e) {
            System.out.println("There was an error opening one of the files.");
        }
    }

    //Clears screen after introduction 
    private static void clearScreen() {
        for (int blanks = 0; blanks < 80; blanks++) {
            System.out.println();
        }
    }

    // This method returns a randomly selected integer
    // between 0 and count-1
    public static int pickrandom(int count) {
        Random generator = new Random();
        return generator.nextInt(count);
    }

    // Places asterisks in place of the letters in the word
    // Parameter is the string word. it holds mystery word

    public static String[] asteriskLine(String word) {
        int i;
        String[] asteriskArray = new String [word.length()];
        for (i = 0; i < word.length(); i++) {

            asteriskArray[i] = "* ";
        }
        return asteriskArray;
    }

    public static void instructions() {
        System.out.println("              H A N G M A N. "
            + "\n This is a word guessing game. "
            + "\n A word will be selected at random and kept hidden. You will try to figure out the secret word by"
            + "\n guessing letters which you think are in the word. "
            + "\n You will guess one letter at a time. "
            + "\n If the letter you guess is correct, the position(s) of the letter in the secret word will be shown. "
            + "\n You will be allowed "
            + NUM_GUESS
            + " wrong guesses  If you guess incorrectly "
            + NUM_GUESS
            + " times, you lose the game. "
            + "\n If you guess all of the letters in the word, you win."
            + "\n\n Press enter to continue ");
    }

    public static String randomWord(Scanner input, int random) {
        String[] dictionaryWords = new String [MAXSIZE];
        int usedsize = 0;
        while (usedsize < MAXSIZE && input.hasNextLine()) {
            dictionaryWords[usedsize] = input.nextLine();
            usedsize++; 
        }

        String word = dictionaryWords[random];
        return word;
    }

    //Replaces correct guess in blanks 
    public static String correctWord(String guess, String word, String asterisk, char letter) { 
        return null;
    }

    public static void printArray(String[] asterisk, String[] charArray, String word, int tries, String[] wrongGuesses, int guessMade) {
        System.out.println("Word to guess");
        for (int count = 0; count < word.length(); count++) { 
            System.out.print(asterisk[count]); 
        }

        System.out.println("\nGuesses remaining: " + tries);

        System.out.print("Incorrect letters tried: ");
        for (int count = 0; count <= guessMade; count++) { 
            System.out.print(wrongGuesses[count] + " "); 
        }
        System.out.println("\nEnter a letter to guess or 9 to quit");

    }

    public static String[] wrongGuesses(int guessMade, String [] wrongGuesses, String letter) {
        wrongGuesses[guessMade] = letter;
        return wrongGuesses;
    }

    public static String[] searchArray(String[] charArray, String[] asterisk, int guessMade, String letter, String word) {
        int[] a = new int[word.length()];
        for (int count = 0; count < word.length(); count++) { 
            if (letter == charArray[count]) {
                asterisk[count] = charArray[count]; 
            }
        }
        return asterisk;

    }
}

2 个答案:

答案 0 :(得分:0)

您需要做的一件事就是只读一次所有单词,然后将它们全部存储到ArrayList中。您当前的代码尝试重新使用已经花费的Scanner对象,但这将失败。而是从ArrayList<String>获取随机单词。

答案 1 :(得分:0)

  

运行调试似乎导致程序崩溃的问题是   这个词有时候会以null为结尾,但有时候却没有   真的知道为什么

db.getCollection('raw_originBusinessData').aggregate([
 { "$match": {
  objectStatus : "UNPROCESSED"
  , $or: [
    { objectOriginAPI : "Profit & Loss"}
    ,{objectOriginAPI : "Balance Sheet"}
    ,{objectOriginAPI : "Bank Summary"}
    ]}
 },
       // don't worry about this, this is all good
 { "$unwind": "$objectRawOriginData.Reports" }
,{ "$unwind": "$objectRawOriginData.Reports.Rows" }
,{ "$unwind": "$objectRawOriginData.Reports.Rows.Rows" },

       // this is where I believe I'm having my problem
 { "$group": {"_id": "$entity_id"
       //    , "$connection_id"
       //    , "objectCycleID"
, "accountBalances": { "$push": "$objectRawOriginData.Reports.Rows.Rows.Cells.Value" }
 }},
{$project: {objectClass: {$literal: "Source Data"}
 , objectCategory: {$literal: "Application"}
 , objectType: {$literal: "Account Balances"}
 , objectOrigin: {$literal: "Xero"} 
 , entity_ID: "$_id"
 , connection_ID: "$connection_ID"
 , accountBalances: "$accountBalances"}
}
 ]
      // ,{$out: "std_sourceBusinessData"}
)

有时 public static String randomWord(Scanner input, int random) { String[] dictionaryWords = new String [MAXSIZE]; int usedsize = 0; while (usedsize < MAXSIZE && input.hasNextLine()) { dictionaryWords[usedsize] = input.nextLine(); usedsize++; } String word = dictionaryWords[random]; return word; } 会大于random。 所以你需要从循环外移动这一行

usedsize

进入此函数,并且最大值为usedsize(或usedsize-1)。

您可以保护自己免受此错误的影响,并通过编写单元测试来确定您是否应该使用usedsize或usedsize-1。查看Junit教程。

在你的junit测试中,调用randomword并将其传递给一个非常高的随机值。然后

 int random = pickrandom(MAXSIZE); 

当随机长度超过字典长度时,Word为空。