public class Basic {
public static void main (String []args){
int first = 1;
if (first == 1);{
System.out.println("I did it");
}
else {
System.out.println("I didnt do it");
}
我不知道该怎么做,是否有错误,我按照教程中的所有步骤观看。它只是说删除令牌
答案 0 :(得分:1)
在if (first == 1);
分号后,if
语句结束,{}
之后的块不是if的一部分。所以else
部分抱怨if不存在if如果没有
答案 1 :(得分:1)
在(first == 1)
答案 2 :(得分:0)
你应该删除明显错位的;
并完成所有打开的括号。试试这个:
public class Basic
{
public static void main (String []args)
{
int first = 1;
if (first == 1)
{
System.out.println("I did it");
}
else
{
System.out.println("I didnt do it");
}
}
}
如果括号有问题,可以将Eclipse配置为自动将闭合括号放在彼此之下,如示例所示。
您放置的分号结束了if
语句,因此它对括号之间的代码没有影响。你可以想象(Java纯粹主义者将赦免简单的解释),在if
之后,只允许一个命令或命令块。括号将更多命令分组到一个块。
试试这个例子,它会解释它是如何工作的。
int i=1;
if (i==1)
System.out.println("I should be here when i==1");
else
System.out.println("Will this output be printed out? No, this is else section!");
if (i==2)
{
System.out.println("I should be here when i==2");
System.out.println("Will this output be printed out? No! Condition was not met, because i==1 and we are in the block");
}
if (i==2)
System.out.println("I should be here when i==2");
System.out.println("Will this output be printed out? Yes, because the commands are not in the block!");
if (i==2); //WATCH OUT, there is semicolon that terminated if statement
System.out.println("Will this output be printed out? Yes, because that semicolon has terminated the if statement!");