【发布时间】:2016-08-23 21:12:49
【问题描述】:
IT 领域的新手,遇到了一些初学者的问题。 所以,我正在阅读一些教程,并遇到了一个我自己无法解决的问题。代码如下:
boolean gameOver = true;
int score = 5000;
int levelCompleted = 5;
int bonus = 100;
if(score == 5000)
System.out.println("Your score is 5000");
if(score > levelCompleted){
System.out.println("Score is greater that levelCompleted");
System.out.println("5000 is greater that 5");
System.out.println("Some new text on true condition");
}
if(score<5000){
System.out.println("Score is equal to 5000");
}
else
{
System.out.println("Condition is false");
}
if((score < 5000) && (score > 1000)){
System.out.println("Both conditions are true");
}
else if(score<1000)
{
System.out.println("Else if condition is true");
}
else
{
System.out.println("None of the condtitions are true!");
if(gameOver == true){
int finalScore = score + (levelCompleted * bonus);
System.out.println("Your final score was " + finalScore);
}
if(gameOver == true){
score = 10000;
levelCompleted = 8;
bonus = 200;
int finalScore= score + (levelCompleted * bonus);
System.out.println("Your final score was " + finalScore);
}
System.out.println(score);
}
System.out.println(levelCompleted);
}
}
上面代码的输出显示了预期的结果,它们是:
Your score is 5000
Score is greater that levelCompleted
5000 is greater that 5
Some new text on true condition
Condition is false
None of the condtitions are true!
Your final score was 5500
Your final score was 11600
10000
8
但是,当我更改 if/else if/else 语句时,if 条件来自
if ( (score < 5000) && (score > 1000) )
到
if( (score == 5000) && (score > 1000) )
如您所见,我只是从
Your score is 5000
Score is greater that levelCompleted
5000 is greater that 5
Some new text on true condition
Condition is false
Both conditions are true
5
那么,下面的另外两个 if-s 发生了什么?
最后两个“独立”system.out.println-s 在哪里?
另外,现在 5 来自哪里?我想来自levelCompleted 变量,但是如何?
提前感谢您的帮助和解释!
【问题讨论】:
-
检查缩进。
-
==true也是多余的。就像*1或+0。注意p==true的结果总是等于p。 -
是的,我知道 if(p==true) 与 if(p) 相同,因为如果默认情况下预计返回 true,但我只是按照教程的节奏和风格写作,作为初学者,这种方式要容易得多。问题是,我还查阅了 oracle 官方文档以及其他一些受人尊敬的文档和书籍,但没有找到有关如何使用许多 if-s、else if-s 和其他潜在问题的答案。
标签: java if-statement conditional