我正在为我的计算机科学课做一个hang子手游戏,似乎无法弄清楚如何解决我的问题与字符串。我遇到了一个越界索引错误。它说为什么我的字符串索引超出范围?
java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:7
在这里发生:
if(theGuess.equals(wordToGuess.substring(i,i+1)))
下面是程序代码,如果它是任何帮助。
import javax.swing.JOptionPane;
public class Hangman extends BasicGame
{
private final String WORDCHOICES= "apple"+"great"+"zebra"+"mouse"+"chick"+"class"+"abhor"+"abide"
+"fuzzy"+"brute"+"blunt"+"comic"+"cater"+"stone"+"chaos"+"dufus"+"earth"+"decal"+"happy"+"heist"
+"idler"+"lions"+"hates"+"idols"+"lasso"+"lives"+"lisps"+"major"+"mound"+"mango"+"meter"+"mercy"
+"marry"+"pilot"+"plots"+"pants"+"overt"+"quack"+"paver"+"polls"+"scorn"+"sapid"+"sails"+"rowdy"
+"seeks"+"leech"+"seats"+"spade"+"shoes"+"slurp";
private String wordToGuess;
private java.util.Random randy;
private int wordNum;
private int numCorrect=0;
private String[] correctLetters= new String[]{"","","","",""};
HangDraw artist= new HangDraw();
public Hangman()
{
super();
randy= new java.util.Random();
for(int i = 0; i<5;i++)
correctLetters[i]=null;
wordNum=0;
numCorrect=0;
artist.setUp();
}
public void guess()
{
wordNum= 5*randy.nextInt(50);
numCorrect=0;
int wrong=0;
String userGuess="";
int partsDrawn=0;
wordToGuess=WORDCHOICES.substring(wordNum,wordNum+5)+" ";
while(numCorrect<5&& partsDrawn<5)
{
userGuess= JOptionPane.showInputDialog("Guess a letter, so far you have: "+ correctLetters[0]+
correctLetters[1]+correctLetters[2]+correctLetters[3]+correctLetters[4]);
if(checkLetter(userGuess))
{
JOptionPane.showMessageDialog(null, "Correct Guess");
//print the letter
}
else
{
//draw the part of the body
JOptionPane.showMessageDialog(null,"incorrect");
partsDrawn++;
artist.drawParts(partsDrawn);
}
}
if(partsDrawn==5)
{
JOptionPane.showMessageDialog(null, "failed to guess, the word is: "+wordToGuess);
}
else
{
JOptionPane.showMessageDialog(null, "correct, the word was: "+ wordToGuess);
}
}
private boolean checkLetter(String theGuess)
{
boolean matches=false;
for(int i=0;i<wordToGuess.length();i++)
{
if(theGuess.equals(wordToGuess.substring(i,i+1)))
{
correctLetters[i]=theGuess;
matches=true;
numCorrect++;
}
}
return matches;
}
}
谢谢您提供
您是否知道'WORDCHOICES'是以下字符串:'applegreatzebramousechickclassabhorabidefuzzybrutebluntcomiccaterstonechaosdufusearthdecalhappyheistidlerlionshatesidolslassoliveslispsmajormoundmangometermercymarrypilotplotspantsovertquackpaverpollsscornsapidsailsrowdyseeksleechseatsspadeshoesslurp'?为什么不使用数组?那么你的话不会被限制在5个字符。 – Cruncher
我不应该使用数组,我的老师想要250个字符的字符串中有50个5个字母的单词,谢谢你的建议,尽管 – abysmaldan
似乎每天都有人在这里有一个由老师组成的不同的疯狂要求。如果你想教字符串操作,那么不要使用一个具有更好的数组/集合解决方案的例子。显然这不是你的错,有时候我真的不明白。 – Cruncher