【问题标题】:Programming Hangman in Java, exception in main thread error (along with others)用Java编程Hangman,主线程错误中的异常(以及其他)
【发布时间】:2014-01-02 14:04:09
【问题描述】:

所以到目前为止,我的这个程序有些功能。我一直在使用 switch 语句。我不确定这是否是正确的逻辑,但我有它的工作。当我输入我想要的单词时,它可以工作,并在第一次输入后开始绘制刽子手,但随后出现错误。

                public class Hangman {
                     public static void main (String[] args){
                       JFrame frame = new JFrame ("Hangman");
                       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                       HangmanPanel Panel = new HangmanPanel();

                       frame.getContentPane().add(Panel);
                       frame.pack();
                       frame.setVisible(true);

                    }


                  }

这是我的另一堂课

   import javax.swing.JPanel;

import java.awt.event.*;

import javax.swing.*;

import java.util.Random;
import java.util.Scanner;
import java.io.*;
import java.util.Scanner;

public class HangmanPanel extends JPanel {
    int lives;
    String guessletter;
    String inputw;
    char[] hiddenWord;
    char[] aOfWord;
    String[] words = { "ADA", "COBOL", "LOGO", "BASIC", "PROLOG", "UBUNTU",
            "UHURU" };

    Scanner scan = new Scanner(System.in);
    boolean isFound;
    int a;

    public HangmanPanel() {

        System.out.println("Enter the word to be searched: ");
        inputw = scan.nextLine();

        aOfWord = inputw.toCharArray();
        this.setLives(inputw.length());
        // this.output();

        hiddenWord = new char[aOfWord.length];

        for (int j = 0; j < hiddenWord.length; j++)
            hiddenWord[j] = '*';

        this.output();

        while (lives > 0)
            System.out.println("Please choose a letter: ");
        guessletter = scan.nextLine();
        this.checkForMatch(guessletter);
        if (isFound == true) {
            hiddenWord[a] = guessletter.charAt(0);
        } else {
            System.out.println("_____");
            System.out.println("|   |");
            System.out.println("|   ");
            System.out.println("|   ");
            System.out.println("|   ");
            this.reduceLives();

            while (lives > 0)
                System.out.println("Please choose a letter: ");
            guessletter = scan.nextLine();
            this.checkForMatch(guessletter);
            if (isFound == true) {
                hiddenWord[a] = guessletter.charAt(1);
            } else {
                System.out.println("_____");
                System.out.println("|   |");
                System.out.println("|   o");
                System.out.println("|    ");
                System.out.println("|    ");
                this.reduceLives();

            }

            while (lives > 0)
                System.out.println("Please choose a letter: ");
            guessletter = scan.nextLine();

            this.checkForMatch(guessletter);
            if (isFound == true) {
                hiddenWord[a] = guessletter.charAt(2);
            } else {
                System.out.println("_____");
                System.out.println("|   |");
                System.out.println("|   o");
                System.out.println("|   | ");
                System.out.println("|    ");
                this.reduceLives();
            }

            while (lives > 0)
                System.out.println("Please choose a letter: ");
            guessletter = scan.nextLine();

            this.checkForMatch(guessletter);
            if (isFound == true) {
                hiddenWord[a] = guessletter.charAt(3);
            } else {
                System.out.println("_____");
                System.out.println("|   |");
                System.out.println("|   o");
                System.out.println("|  /| ");
                System.out.println("|    ");
                this.reduceLives();
            }

            while (lives > 0)

                System.out.println("Please choose a letter: ");
            guessletter = scan.nextLine();

            this.checkForMatch(guessletter);
            if (isFound == true) {
                hiddenWord[a] = guessletter.charAt(4);
            } else {
                System.out.println("_____");
                System.out.println("|   |");
                System.out.println("|   o");
                System.out.println("|  /|\\ ");
                System.out.println("|    ");
                this.reduceLives();
            }

            while (lives > 0)

                System.out.println("Please choose a letter: ");
            guessletter = scan.nextLine();

            this.checkForMatch(guessletter);
            if (isFound == true) {
                hiddenWord[a] = guessletter.charAt(5);
            } else {
                System.out.println("_____");
                System.out.println("|   |");
                System.out.println("|   o");
                System.out.println("|  /|\\ ");
                System.out.println("|    \\");
                this.reduceLives();
            }

            while (lives > 0)

                System.out.println("Please choose a letter: ");
            guessletter = scan.nextLine();

            this.checkForMatch(guessletter);
            if (isFound == true) {
                hiddenWord[a] = guessletter.charAt(6);
            } else {
                System.out.println("_____");
                System.out.println("|   |");
                System.out.println("|   o");
                System.out.println("|  /|\\");
                System.out.println("|  / \\");
                this.reduceLives();
            }


        }
        this.output();

    }

    public void setLives(int a) {
        this.lives = a;
    }

    public void reduceLives() {
        lives = lives - 1;
        System.out.println("Lives remaining: " + this.getLives());

    }

    public int getLives() {
        return lives;
    }

    public void output() {
        System.out.println("Lives remaining: " + this.getLives());
        System.out.println("Word found so far ");

        for (int i = 0; i < hiddenWord.length; i++) {
            System.out.print(hiddenWord[i] + "\n");
        }

    }

    public void checkForMatch(String l) {

        for (int i = 0; i < aOfWord.length; i++) {

            if (l.charAt(0) == aOfWord[i]) {
                isFound = true;
                a = i;
                break;
            } else {
                isFound = false;
            }
        }

    }
}

【问题讨论】:

  • 请在这里发布错误?
  • 您没有在每个case 之后使用breakreturn,因此您的代码可能正在按程序运行并给您带来意外错误。
  • 我不认为在这种情况下休息会很重要,因为所有情况都是相互排斥的。
  • 抱歉,这是错误“线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:HangmanPanel 的 java.lang.String.charAt(Unknown Source) 处的 4。(HangmanPanel.java:115) 在 Hangman.main(Hangman.java:12)
  • @MxyL OP 应该删除 switch 语句,如果是这样的话,因为它不需要。有break 的好形式,这样你就可以理解程序流程,特别是因为他有一个loop 迭代案例直到lives

标签: java exception main


【解决方案1】:

我想你现在已经掌握了这一点,但我很好奇,所以我对你的课程进行了拍摄,并评论了我的更改。希望您或其他人可以使用它:-]

// renamed from Hangman
public class Main {
    public static void main(String[] args) {

        // removed need for JFrame as no GUI is actually used.
        Hangman hangman = new Hangman();
        // starting a thread with the hangman runnable
        new Thread(hangman).start();

        // main thread will end here, but the hangman thread will keep the program running. 
    }
}

然后才是真正的 Hangman 类:

import java.util.Arrays;
import java.util.Scanner;


// Renamed from HangmanPanel, changed from JPanel to Runnable since no GUI is shown.
public class Hangman implements Runnable {

    // always use 7 lives, as this is the number of "hangman images" in reduceLives()
    private int lives = 7;

    private char[] hiddenWord;
    private char[] aOfWord;

    // I'm guessing that at some point you will use these randomly? 
    private String[] words = { "ADA", "COBOL", "LOGO", "BASIC", "PROLOG", "UBUNTU", "UHURU" };


    @Override
    public void run() {
        // This is the new Try-With-Resources in Java 7.
        // If you don't have Java 7, just change the 
        // try ( Scanner scan = new Scanner(System.in) ) {
        // to
        // try {
        //   Scanner scan = new Scanner(System.in);
        try ( Scanner scan = new Scanner(System.in) ) {

            System.out.println("Enter the word to be searched: ");
            String inputw = scan.nextLine();

            aOfWord = inputw.toCharArray();
            hiddenWord = new char[aOfWord.length];

            // nice method for filling an array.
            Arrays.fill(hiddenWord, '_');

            // renamed from output
            showStatus();

            // fixed outer while-loop
            while (lives > 0 && Arrays.equals(aOfWord, hiddenWord) == false) {
                System.out.println("Please choose a letter: ");
                String guessletter = scan.nextLine();
                if(guessletter.isEmpty()) {
                    System.out.println("You must enter a letter. Try again!");
                } else {
                    checkForMatch(guessletter);
                }

                // refactored all inner loops into checkForMatch() and reduceLives()
            }

            System.out.println("Game over, you " + (lives > 0 ? "won" : "lost"));   
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    private void checkForMatch(String letter) {
        boolean found = false;

        for (int i = 0; i < aOfWord.length; i++) {
            if (letter.charAt(0) == aOfWord[i]) {
                found = true;
                hiddenWord[i] = letter.charAt(0);
                // removed break when found to allow searching entire word
            }
            // removed else condition to avoid clearing 'found' when searching rest of word
        }

        if(!found) {
            // reduceLives() will also print new hangman 
            reduceLives();
        }

        // printing summary
        showStatus();
    }

    private void reduceLives() {
        lives = lives - 1;

        switch (lives) {
        case 6:
            System.out.println("_____");
            System.out.println("|   |");
            System.out.println("|   ");
            System.out.println("|   ");
            System.out.println("|   ");

            break;
        case 5:

            System.out.println("_____");
            System.out.println("|   |");
            System.out.println("|   o");
            System.out.println("|    ");
            System.out.println("|    ");

            break;
        case 4:
            System.out.println("_____");
            System.out.println("|   |");
            System.out.println("|   o");
            System.out.println("|   | ");
            System.out.println("|    ");

            break;
        case 3:
            System.out.println("_____");
            System.out.println("|   |");
            System.out.println("|   o");
            System.out.println("|  /| ");
            System.out.println("|    ");

            break;
        case 2:
            System.out.println("_____");
            System.out.println("|   |");
            System.out.println("|   o");
            System.out.println("|  /|\\ ");
            System.out.println("|    ");

            break;
        case 1:
            System.out.println("_____");
            System.out.println("|   |");
            System.out.println("|   o");
            System.out.println("|  /|\\ ");
            System.out.println("|    \\");

            break;
        case 0:
            System.out.println("_____");
            System.out.println("|   |");
            System.out.println("|   o");
            System.out.println("|  /|\\");
            System.out.println("|  / \\");

            break;
        }

    }

    private void showStatus() {
        System.out.println("Lives remaining: " + lives);
        System.out.println("Word found so far " + new String(hiddenWord));
    }
}

【讨论】:

  • 谢谢。这很有帮助。我无法完全弄清楚我的作业,所以我只是把它交出来以获得一些功劳。但很高兴看到它是如何工作的。我将其复制并粘贴到我的编辑器中。我以后肯定会以此为参考。谢谢。
【解决方案2】:

您的代码按照现在的编写方式执行失败。它进入一个案例,由于您没有 break,它进入下一个案例。您需要在案例中的每个 else 语句之后输入 break

例子

case 1:
            System.out.println("Please choose a letter: ");
            guessletter = scan.nextLine();
            this.checkForMatch(guessletter);
            if (isFound == true) {
                hiddenWord[a] = guessletter.charAt(0);
            } else {
                System.out.println("_____");
                System.out.println("|   |");
                System.out.println("|   ");
                System.out.println("|   ");
                System.out.println("|   ");
                this.reduceLives();
            }
            break;                                   // Add this for each case

【讨论】:

  • 谢谢。刚试过。我仍然在主线程错误中遇到异常。我将尝试删除 switch 语句并执行 if else
  • 好的。祝您好运,如果您还有其他问题,请随时提出。您还说您是初学者,所以这里有一本好书的链接,我建议您阅读。 link
  • 谢谢伙计。好吧,我将所有这些 switch 语句都更改为 while (lives > 0) then if else for each and each。不是当我运行它时,它会在无限循环中打印出“请选择一个字母”
  • 所以你对上面代码的问题是它只会进入第一个while循环,然后不断地打印出语句,因为生命总是大于零。我建议您阅读链接中的书,然后尝试编写代码。修复此代码需要大量工作。
  • 我真的没有时间阅读整本书。看来我的老师会布置高于我们技能水平的作业来测试我们。我下载了这本书,我会在圣诞假期开始阅读。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 2013-03-13
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多