ava.lang.StringIndexOutOfBoundsException:字符串索引超出范围:9 at java.lang.String.charAt(String.java:658)
ava.lang.StringIndexOutOfBoundsException: String index out of range: 9 at java.lang.String.charAt(String.java:658)
所以我有这段代码。
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;
}
}
}
}
}
它编译得很好但是当我输入第一个字符并输入时它给我这个错误:
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)
我想做的是从字符串中读取字符,而不是创建一个包含所有字符的数组。有帮助吗?
改变
for(x = 0; x < num +1; x++)
到
for(x = 0; x < num; x++)
你也可能是说
for(boolean guessed = false; guessed == true;) // notice == instead
然后在此(外部)for
循环中将此标志设置为 true
。
所以我有这段代码。
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;
}
}
}
}
}
它编译得很好但是当我输入第一个字符并输入时它给我这个错误:
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)
我想做的是从字符串中读取字符,而不是创建一个包含所有字符的数组。有帮助吗?
改变
for(x = 0; x < num +1; x++)
到
for(x = 0; x < num; x++)
你也可能是说
for(boolean guessed = false; guessed == true;) // notice == instead
然后在此(外部)for
循环中将此标志设置为 true
。