java - String index out of range on button pressed -


having problems little hangman game i'm making.

private void btntactionperformed(java.awt.event.actionevent evt)  {                                          btnt.setenabled(false);               if(word.charat(0)=='t'){         lblspace1.settext("t");     }     if(word.charat(1)=='t'){         lblspace2.settext("t");     }     if(word.charat(2)=='t'){         lblspace3.settext("t");     }             if(word.charat(3)=='t'){         lblspace4.settext("t");     }             if(word.charat(4)=='t'){         lblspace5.settext("t");     }             if(word.charat(5)=='t'){         lblspace6.settext("t");     }             if(word.charat(6)=='t'){         lblspace7.settext("t");     }             if(word.charat(7)=='t'){         lblspace8.settext("t");     }             if(word.charat(8)=='t'){         lblspace9.settext("t");     }             if(word.charat(9)=='t'){         lblspace10.settext("t");     }     if(!word.contains("t")){         guessesleft--;         lblguessesleft.settext("number: "+guessesleft+"");                 } } 

the code checks if letter t in each space of word. however, words aren't 10 characters long, error "string index out of range" printed.

is there way check the letters in word?

you can this:

@override public void actionperformed(actionevent e) {      for(int = 0; < word.length(); ++i)          if(word.charat(i) == 't')//if condition true         {                  //that means character @ position `i`             switch (i)             {                 case 1:                     lblspace1.settext("t");                     break;                 case 2:                     // other stuff                     break;                 default:                     break;             }         } } 

you cannot have problems of type indexoutofrange code.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -