简体   繁体   English

Bingo歌词代码Java.lang.stringindexoutofbounds?

[英]Bingo Lyrics Code Java.lang.stringindexoutofbounds?

I am new to programming and I have written a bingo class that types out the lyrics to bingo. 我是编程新手,我编写了一个Bingo类,将歌词键入Bingo。 Here is the code: 这是代码:

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

It works but i get a java.lang.stringindexoutofbounds for the line lineTwo = "*" + (lineTwo.substring(starCount)) ; 它可以工作,但我得到lineTwo =“ *” +(lineTwo.substring(starCount))的java.lang.stringindexoutofbounds; . Why does it do this? 为什么这样做呢? Any way to fix? 有什么办法解决?

You get an StringOutOfBoundsException because at the last iteration of the loop the starCount is 6, but the string is only five characters long. 之所以得到StringOutOfBoundsException,是因为在循环的最后一次迭代中,starCount为6,但是字符串只有五个字符长。 Instead of using a string for line two, you can use a StringBuilder. 您可以使用StringBuilder代替第二行使用字符串。 It's easier because you can replace a char at a specified index. 这很容易,因为您可以在指定的索引处替换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;
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM