我是java的新手,我继续抛出这个异常,我使用mysWord.length的方式是错误还是.charAt(i)的问题?
public static int setGuessdLetters(String mysWord)
{
word.letters = new char[mysWord.length()];
word.guesdletters = new char[mysWord.length()];
for(int i = 0; i <= mysWord.length(); i++)
{
word.letters[i] = mysWord.charAt(i);
word.guesdletters[i] = '_';
}
return(mysWord.length());
}
错误读取:
请输入一个单词(最多14个字符):apple
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:658)
at hangman.Hangman.setGuessdLetters(Hangman.java:206)
at hangman.Hangman.main(Hangman.java:258)
Java结果:1
建立成功(总时间:2秒)
答案 0 :(得分:0)
只需将less than equalto(<=)
替换为less than(<)
。
Java数组索引从0
开始到length -1
。这就是为什么你得到OutOfBoundsException
for(int i = 0; i < mysWord.length(); i++)
{
word.letters[i] = mysWord.charAt(i);
word.guesdletters[i] = '_';
}