在三元运算符声明中非法开始表达

jut*_*eni 0 java if-statement ternary-operator

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");
                }


    }
}
Run Code Online (Sandbox Code Playgroud)

我需要制作一个允许输入一年的程序,程序需要判断那一年(我们在控制台上输入的)是否是闰年.

年份可分为4年,不可分为100个IS闰年.可分为400年的年份,也可以按100 IS闰年分类.

我需要使用"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.
Run Code Online (Sandbox Code Playgroud)

Ste*_*han 5

String result = (rest3 == 0 && rest2 != 0 || rest == 0 && rest2 == 0 ) ? "Leap year" :  "Not leap year";
Run Code Online (Sandbox Code Playgroud)

删除;)最后一个字符;.

最后你的代码应如下所示:

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");
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

result是一个String,它不能与布尔值(true)进行比较.改用equals方法.请注意,equals区分大小写.它的部分是equalsIgnoreCase.