java - 三元运算符语句上的表达式开始非法

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


    }
}

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

能被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/

相关文章:

javascript - Google 脚本 - 用于多张工作表的一个运行编辑脚本

javascript - 基于eslint改进js代码

java - 如何在axis生成的客户端中实现线程以使用java向web服务发出多个请求

java - 在没有项目的情况下在 Eclipse 中导航导入

java - 与复合实体键的双向 OneToMany 关系导致空标识符

php - 如何退出if语句并继续else

bash - Bash 中的 "$#"特殊参数是什么意思?

swift - 如何在三元条件运算符中使用 Optional 变量?

vb.net - IIf 抛出奇怪的异常

java - 如何在 JSpinner 上只显示日期