【问题标题】:(index out of bounds) I wrote a hangman game program with java [duplicate](索引超出范围)我用java写了一个刽子手游戏程序[重复]
【发布时间】:2017-11-27 13:15:05
【问题描述】:

我确信我的程序还有许多其他问题,但我目前被困在这个问题上并专注于首先解决这个问题。 我的目标是在更改游戏编号的同时根据输入的单词数循环游戏。 我的问题是“显示横幅”部分一直循环,直到遇到“超出边界”的错误。当我输入“java Hangman 123 test”时显示如下:

========
Game: 1
========
Game: 2
========
Game: 3
========
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Hangman.main(Hangman.java:121)

这是我的程序:

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;

public class Hangman {

    //validation of raw questions
    public static boolean isValidQuestion(String rawQuestion){
        rawQuestion = rawQuestion.toUpperCase();
        boolean vQuestion = true;
        for(int i=0; i<rawQuestion.length(); i++){
            char c = rawQuestion.charAt(i);

            if(!(c>='A' && c<='Z'))
            vQuestion = false;
        }
        return vQuestion;
    }

    //show invalid tries
    public static String formatCharArray(char[] ca){
        String output = "";
        for(int i=0; i<ca.length; i++){
            output += ca[i] + " ";
        }
        return output;
    }

    public static void main(String args[]){

        if(args.length==0){
            System.out.println("Usage: java Hangman word_to_guess [more_word_to_quess]...");
            return;
        }

        List<String> validQuestions = new ArrayList<>();
        for (int i = 0; i < args.length; i++){
            String rawQuestion = args[i];
            boolean b = isValidQuestion(rawQuestion);
            if (b){
                validQuestions.add(rawQuestion);
            }else{
                System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
            }
        }

        // store valid questions into an array
        String questions[] = validQuestions.toArray(new String[validQuestions.size()]);

        // shuffle the questions
        for(int i=0; i<7; i++){
            int x = (int)(Math.random()*validQuestions.size());
            int y = (int)(Math.random()*validQuestions.size());
            String temp = questions[x];
            questions[x] = questions[y];
            questions[y] = temp;
        }

        // game

        // initiallize
        int noInvalidTry = 0;
        int count = 0;
        char[] invalidTries = new char[6];
        int j = 0;
        char[] userGuess = new char[questions[j].length() ];
        boolean isCorrect = false;

        for(int i=0; i<invalidTries.length; i++){
            invalidTries[i] = '_';
        }

        for(int k=0; k<userGuess.length; k++){
            userGuess[k] = '_';
        }

这是我搞砸的部分。

        // display banner

        while( j<= args.length){
            System.out.println( "========" );
            System.out.println( "Game: " + ++j );
            System.out.println("========");

        }

上面

        // game loop

        while( noInvalidTry<6 && count<questions[j].length() ){
            Scanner sc= new Scanner(System.in);

            System.out.print("Please input your guess: ");
            String s = sc.nextLine().trim();

            // check input length
            while(s.length()==1 && isValidQuestion(s)){

                //start guess
                char inputChar = s.charAt(0);
                inputChar = Character.toUpperCase(inputChar);

                boolean c = false;
                for(int i=0; i<questions[j].length(); i++){
                    if((s.equals(questions[j].charAt(i))) && (userGuess[i] == '_')){
                        //update userGuess
                        userGuess[i] = questions[j].charAt(i);
                        c = true;
                        count++;
                        System.out.println( "Good try!" );
                        // show status
                        System.out.printf("No of Invalid try: %d/6\t\tInvalid tries: ",noInvalidTry);
                        System.out.println( formatCharArray(invalidTries) );

                    }
                }
                if(!c){
                    noInvalidTry++;
                    System.out.println( "Oops..." );
                    // show status
                    System.out.printf("No of Invalid try: %d/6\t\tInvalid tries: ",noInvalidTry);
                    System.out.println( formatCharArray(invalidTries) );
                }
            }
        }
        if( noInvalidTry==6 && count<questions[j].length()){
            System.out.println("Game over, the answer is " + questions[j] );
            j=j++;
        }
        if( noInvalidTry<6 && count==questions[j].length()){
            System.out.println("Congratulation!");
            j=j++;
        }
        //final status
        if(j==args.length){
            double temp = 0;
            double score = 0;
            double total = args.length;
            System.out.println("-------------------------------------------------------------------------------------------------------------------");
            System.out.println("Summary");
            System.out.println("-------------------------------------------------------------------------------------------------------------------");
            while(j<=args.length && isCorrect ){
                System.out.println(++j + ". " + questions[j] + "\t" + "Correct" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
                temp++;
            }
            while(j<=args.length && !isCorrect) {
                System.out.println(++j + ". " + questions[j] + "\t" + "Incorrect" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
            }
            score = temp/total;
            System.out.println("Final result: " + score + " / 100 marks");
            System.out.println("-------------------------------------------------------------------------------------------------------------------");
        }


    }
}

【问题讨论】:

标签: java arrays indexoutofboundsexception


【解决方案1】:
    if(j==args.length){

        // ...

        while(j<=args.length && isCorrect ){
            System.out.println(++j + "" + questions[j] + "\t" + "Correct" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
            temp++;
        }
        while(j<=args.length && !isCorrect) {
            System.out.println(++j + ". " + questions[j] + "\t" + "Incorrect" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
        }

如果j是数组长度,那么questions[j]引发错误(最后一个元素是length-1)

但是,更糟糕的是,您仍在增加j 甚至更多(2 个j++ 语句)!

它们在您的 while 循环中还有许多其他 j++


作为一种帮助您处理数组的好习惯:当您对作为索引的值进行一些迭代时:

  • 更喜欢 for 循环
  • 循环获取参数的正确值(在0length-1 之间)
  • 不要随机增加数组,您应该确定您的数组索引 (j) 增加一次且每次迭代仅增加一次。为了帮助您做到这一点,您应该在循环中只使用一行声明 j++++j,而不是在一些 if 块中嵌套在不同位置的一些 j++
  • (这就是为什么建议使用for 循环的原因:j++ 有一些地方可以做,如果没有非常好的理由,你不应该在其他地方做。

另外,如 cmets 中所述,您应该学会分析错误 (What is a stack trace, and how can I use it to debug my application errors?),并使用调试工具并逐步检查您的程序,看看您对所有变量做了什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2015-05-29
    相关资源
    最近更新 更多