Bingo歌词代码Java.lang.stringindexoutofbounds?

时间:2013-12-05 03:16:48

标签: 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 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 for line lineTwo =“*”+(lineTwo.substring(starCount)); 。为什么这样做?有什么方法可以修复吗?

1 个答案:

答案 0 :(得分:0)

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

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;
    }
}

}