我是编程新手,我已经编写了一个bingo类,用于输入bingo的歌词。代码如下:
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 ;
}
}
}它可以工作,但我得到了行lineTwo = "*“+ (lineTwo.substring(starCount));的java.lang.stringindexoutofbounds。它为什么要这样做?有什么办法可以解决吗?
发布于 2013-12-05 11:41:18
您会得到一个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;
}
}}
https://stackoverflow.com/questions/20390732
复制相似问题