当我执行这部分代码时,我收到一个 StackOverflowError:
/**
* Determine the story based on the time.
*/
private void timeTell()
{
if(replay == 0){
long rndNum = System.currentTimeMillis() % 10;
chooseStory();
}
}
/**
* Randomly choose which story to tell based on the current system time.
*/
private void chooseStory()
{
if(rndNum == 1&& rndNum == 6){
storyOne();
}
else if(rndNum == 2&& rndNum == 7){
storyTwo();
}
else if(rndNum == 3&& rndNum == 8){
storyThree();
}
else if(rndNum == 4&& rndNum == 9){
storyFour();
}
else if(rndNum == 5&& rndNum == 0){
storyFive();
}
else{
timeTell();
}
}
我知道我不需要 timeTell()
方法,解决这个问题后我会将其添加到 chooseStory()
方法中。这更容易测试。我试图找出问题发生的位置,因此我将 chooseStory();
替换为 System.out.println(rndNum);
并且它打印了两次数字。变量replay
用于查看程序是否已经运行过一次。如果用户决定再次播放,replay
将从默认值 0 更改为 1,并跳过生成新的 rndNum
。我使用时间而不是随机数生成器的原因是因为每次我运行程序时,生成器每次都会给我相同的序列。任何帮助将不胜感激。
最佳答案
您使用了错误的 boolean 运算符。
rndNum == x && rndNum == y
当且仅当 rndNum 等于 x 和 y 时才会通过 - 如果 x 和 y 是不同的值,则永远不会发生这种情况。您需要使用 OR 运算符“||
”:
rndNum == X || rndNum == y
此外,正如 @Sotirios Delimanolis 指出的那样,您还进行了可变屏蔽。他还解释了为什么会发生 StackOverflowError
关于Java:溢出和打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18689097/