Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

ava.lang.StringIndexOutOfBoundsException: String index out of range: 9 at java.lang.String.charAt(String.java:658)

So I have this piece of code.

class Hangman {
public static void main(String[] args) {
    char LetterGuess;
    int x;
    int num = 0;                                    //Number of letters in a word
    int y = 0; //(int)(Math.random() * 16 );
    char CurrLet;
    String word = "yes" ;
    byte[] Guess = new byte[15];

    switch(y) {

        case 0:
            word = "blindfold" ;
            num = word.length();
            break;
    }
    for(boolean guessed = false; guessed = true;) {

        for(x = 0; x < num +1; x++) {
                 if(Guess[x] == 1) {
                    CurrLet = word.charAt(x);
                    System.out.print(CurrLet);
                 } else {
                     System.out.print(" _");
            }
        }

         System.out.println("");
         System.out.println("");
         LetterGuess = Keyboard.readChar();

         for(x = 0; x < num +1; x++) {
            CurrLet = word.charAt(x);
            if(LetterGuess == CurrLet) {
                Guess[x] = 1;
            }
         }


    }

}

}

It compiles fine but when I type in the first char and enter it gives me this error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9 at java.lang.String.charAt(String.java:658) at Hangman.main(Hangman.java:34)

What I am trying to do is read characters off a string without making an array containing all of the characters. Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change

for(x = 0; x < num +1; x++)

to

for(x = 0; x < num; x++)

Also you might have meant

for(boolean guessed = false; guessed == true;) // notice == instead

and then setting this flag to true within this(outer) for loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...