错误:else 没有 if。什么地方出了错?

-14 java if-statement

以下代码产生了elsewithout的编译错误if。其他一切都很好。我也想知道如何评论一些东西。

import java.util.Scanner;

public class CalcRunner
{
    public static void main(String args[])
    {
        System.out.println("Enter 1 to Add, 2 to Subtract, 3 to Divide, or 4 to Multiply");
        int x = keyboard.nextInt();

        if (x == 1);
        {
            System.out.println("Enter an integer");
            int num1 = keyboard.nextInt();

            System.out.println("Enter another integer");
            int num2 = keyboard.nextInt();

            System.out.println("The sum of the numbers equals " + (num1+num2));
        }
        if (x == 2);
        {
            System.out.println("Enter an integer");
            int num1 = keyboard.nextInt();

            System.out.println("Enter another integer");
            int num2 = keyboard.nextInt();

            System.out.println("The sum of the numbers equals " + (num1-num2));
        }
        if (x == 3);
        {
            System.out.println("Enter an integer");
            int num1 = keyboard.nextInt();

            System.out.println("Enter another integer");
            int num2 = keyboard.nextInt();

            System.out.println("The sum of the numbers equals " + (num1/num2));
        }
        if (x == 4);
        {
            System.out.println("Enter an integer");
            int num1 = keyboard.next=Int();

            System.out.println("Enter another integer");
            int num2 = keyboard.nextInt();

            System.out.println("The sum of the numbers equals " + (num1*num2));
        }
        else
        {
            System.out.print("Error 510038585832857329457294547243344684643734");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 7

改变

if (x == 1);

if (x == 1)

在这种情况下,分号是错误的。它会导致{...}始终执行其后的块。

你可能想ifif- else if-...-替换这些语句else

if (x == 1) {
...
} else if (...) {
...
} else if (...) {
...
else {
...
}
Run Code Online (Sandbox Code Playgroud)

因为如果其中一个条件评估为真,则其他条件都不能评估为真,并且我假设您希望else仅当所有条件都为假(而不仅仅是最后一个条件)时才执行该子句。

或者更好的是,使用 switch 语句。

  • @MarounMaroun 求不同意见——说 ** 没有 ** 错误可能会让每个人都感到困惑。这是“语法上合法的”,但仍然**错误**。没有正当理由在 `if` 上使用这种语法。(有时,在`while` 或`for` 上。但从来没有在`if` 上。) (2认同)