宾果歌词代码Java.lang.stringindexoutofbounds?

宾果歌词代码Java.lang.stringindexoutofbounds?,java,string,indexing,Java,String,Indexing,我是编程新手,我已经写了一个宾果类,输入宾果的歌词。代码如下: public class BingoLyrics { String lineOne = "There was a farmer had a dog and Bingo was his name, oh." ; String lineTwo = "BINGO" ; String lineThree = "And Bingo was his name, oh." ; int starCount = 1 ; public void bin

我是编程新手,我已经写了一个宾果类,输入宾果的歌词。代码如下:

public class BingoLyrics {
String lineOne = "There was a farmer had a dog and Bingo was his name, oh." ;
String lineTwo = "BINGO" ;
String lineThree = "And Bingo was his name, oh." ;
int starCount = 1 ;
public void bingoLyrics ( ) {
    while (starCount != 7) {
System.out.println (lineOne) ;
System.out.println (lineTwo + ", " + lineTwo + ", " +  lineTwo) ;
System.out.println (lineThree) ;
lineTwo = "*" + (lineTwo.substring(starCount)) ;
if (lineTwo.length() == 4) {
    lineTwo = "*" + lineTwo ;
}
else if (lineTwo.length() == 3) {
    lineTwo = "**" + lineTwo;
}
else if (lineTwo.length() == 2) {
    lineTwo = "***" + lineTwo;
}
else if (lineTwo.length() == 1) {
    lineTwo = "****" + lineTwo;
}
starCount = starCount + 1 ;
 }
 }
 }

它可以工作,但我得到一个java.lang.stringindexoutofbounds,用于lineTwo=“*”+(lineTwo.substring(starCount))。为什么会这样?有什么方法可以修复吗?

您会得到StringOutOfBoundsException,因为在循环的最后一次迭代中,starCount是6,但字符串只有5个字符长。您可以使用StringBuilder,而不是第二行使用字符串。这更容易,因为您可以在指定的索引处替换字符

public class BingoLyrics {
String lineOne = "There was a farmer had a dog and Bingo was his name, oh.";
StringBuilder lineTwo = new StringBuilder("BINGO");
String lineThree = "And Bingo was his name, oh.";
int starCount = 0;

public void bingoLyrics() {
    while (starCount < 6) {
        System.out.println(lineOne);
        System.out.println(lineTwo + ", " + lineTwo + ", " + lineTwo);
        System.out.println(lineThree);
        lineTwo.replace(starCount, starCount + 1, "*");
        starCount = starCount + 1;
    }
}
public-class-BingoLyrics{
String lineOne=“有一个农夫养了一条狗,他的名字叫宾果,噢。”;
StringBuilder lineTwo=新的StringBuilder(“宾果”);
String lineThree=“宾果是他的名字,哦。”;
int starCount=0;
公共政策{
而(星数<6){
System.out.println(第1行);
System.out.println(lineTwo+“,“+lineTwo+”,“+lineTwo”);
System.out.println(第三行);
第二行。替换(开始计数,开始计数+1,“*”);
starCount=starCount+1;
}
}
}