public class V0206 {
public static void main(String[] args) {
java.util.Scanner sc = new java.util.Scanner(System.in);
int x = sc.nextInt();
int y = 400;
int z = 100;
int q = 4;
int rest =(int)(x % y);
int rest2 = (int)(x % z);
int rest3 = (int) (x % q);
String result = (rest3 == 0 && rest2 != 0 || rest == 0 && rest2 == 0 ) ? "Leap year" : "Not leap year";);
if (result = true) {System.out.println("Leap year");}
else
{System.out.println("Not leap year");
}
}
}
我需要制作一个允许输入年份的程序,并且该程序需要判断该年份(我们在控制台上输入的)是否是闰年。
能被4整除且不能被100整除的年份是闰年。 能被 400 整除的年份,也能被 100 整除的年份是闰年。
我需要使用“if”命令进行流量控制和三元运算符。
编译器给出:
V0206.java:15: error: illegal start of expression
String result = (rest3 == 0 && rest2 != 0 || rest == 0 && rest2 == 0 ) ? "Leap year" : "Not leap year";);
1 error
Compilation failed.
最佳答案
String result = (rest3 == 0 && rest2 != 0 || rest == 0 && rest2 == 0 ) ? "Leap year" : "Not leap year";
删除最后一个 ;
之前的 ;)
字符。
最后你的代码应该如下所示:
public class V0206 {
public static void main(String[] args) {
java.util.Scanner sc = new java.util.Scanner(System.in);
int x = sc.nextInt();
int y = 400;
int z = 100;
int q = 4;
int rest = (int) (x % y);
int rest2 = (int) (x % z);
int rest3 = (int) (x % q);
String result = (rest3 == 0 && rest2 != 0 || rest == 0 && rest2 == 0) ? "Leap year" : "Not leap year";
// This if statement can be replaced by System.out.println(result);
if (result.equals("Leap year")) {
System.out.println("Leap year");
} else {
System.out.println("Not leap year");
}
}
}
result
是一个字符串,不能与 boolean 值 (true
) 进行比较。请改用 equals
方法。请注意,equals
区分大小写。它的对应部分是equalsIgnoreCase
。
关于java - 三元运算符语句上的表达式开始非法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20681601/