gpt4 book ai didi

java - 为什么我的字符串索引超出范围?

转载 作者:行者123 更新时间:2023-12-01 18:41:53 25 4
gpt4 key购买 nike

我正在为我的计算机科学类(class)制作一个刽子手游戏,但似乎不知道如何解决我的字符串问题。我收到索引越界错误。它说

java.lang.StringIndexOutOfBoundsException: String index out of range: 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;
}

}

感谢您提供的任何帮助

最佳答案

根据javadocs , String#substring 抛出一个 IndexOutOfBoundsException

if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

在循环的最后一次迭代中,i 将等于字符串的length,并且 i+1 大于该长度字符串,因此异常(exception)。

所以你需要改变:

for(int i=0;i<=wordToGuess.length();i++)

for(int i=0;i<wordToGuess.length();i++)
^^^

关于java - 为什么我的字符串索引超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19664871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com