Note that there are some explanatory texts on larger screens.

plurals
  1. POwhy my string index is out of range?
    text
    copied!<p>I am making a hangman game for my ap computer science class and could not seem to figure out how to fix my problem with the strings. I am getting an out of bounds index error. it says</p> <blockquote> <p>java.lang.StringIndexOutOfBoundsException: String index out of range: 7 </p> </blockquote> <p>occurring here: </p> <pre><code>if(theGuess.equals(wordToGuess.substring(i,i+1))) </code></pre> <p>Here is the program code if it is any help.</p> <pre><code>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&lt;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&lt;5&amp;&amp; partsDrawn&lt;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&lt;wordToGuess.length();i++) { if(theGuess.equals(wordToGuess.substring(i,i+1))) { correctLetters[i]=theGuess; matches=true; numCorrect++; } } return matches; } } </code></pre> <p>Thank you for any help you provide</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload