首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >宾果歌词代码Java.lang.stringindexoutofbounds?

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

Stack Overflow用户
提问于 2013-12-05 11:16:48
回答 1查看 516关注 0票数 0

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

代码语言:javascript
复制
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。它为什么要这样做?有什么办法可以解决吗?

EN

回答 1

Stack Overflow用户

发布于 2013-12-05 11:41:18

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

代码语言:javascript
复制
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;
    }
}

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20390732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档