语法错误很简单

时间:2015-10-31 20:32:39

标签: java

import java.io.PrintStream;
import java.util.Scanner;

public class BasicCalculator
{
  public static void main(String[] args)
  {
    int ADDITION = 1;
    int SUBTRACTION = 2;
    int MULTIPLICATION = 3;
    int DIVISION = 4;
    int EXIT = 5;

    Scanner keyboard = new Scanner(System.in);
    int choice;
    do
    {
      System.out.println("Choose from the following:");
      System.out.println("1. Add 2 integers");
      System.out.println("2. Subtract 2 integers");
      System.out.println("3. Multiply 2 integers");
      System.out.println("4. Divide 2 integers");
      System.out.println("5. Exit");
      System.out.print("Enter choice: ");
      choice = keyboard.nextInt();
      if ((choice == 1) || (choice == 2) || (choice == 3) || (choice == 4))
      {
        System.out.print("Enter first integer: ");
        int left = keyboard.nextInt();
        System.out.print("Enter second integer: ");
        int right = keyboard.nextInt();
        switch (choice)
        {
        double Result;
        case 1: 
           Result = left + right;
          System.out.println(left + " + " + right + " = " + Result);
          break;
        case 2: 
           Result = left - right;
          System.out.println(left + " - " + right + " = " + Result);
          break;
        case 3: 
           Result = left * right;
          System.out.println(left + " * " + right + " = " + Result);
          break;
        case 4:
          Result = left / right;
          System.out.println(left + " / " + right + " = " + Result);
        }
        System.out.println();
      }
    } while (choice != 5);
  }
}

错误:

BasicCalculator.java:34: error: case, default, or '}' expected
        int Result;
        ^
BasicCalculator.java:34: error: case, default, or '}' expected
        int Result;
            ^
BasicCalculator.java:34: error: case, default, or '}' expected
        int Result;

上面的代码是我的计算机编程类介绍的项目,我遇到了一些源于格式问题的错误。我可以得到一些基本的帮助来解决导致错误的问题。我仍然习惯于在记事本++中阅读错误描述并理解它们的意思。

2 个答案:

答案 0 :(得分:2)

您无法在switch标签之外的case语句中声明 in 。如果您希望在所有Result之间共享case,包括default,请在switch之前声明它,如下所示:

double Result = 0;
switch (choice)
{
case 1: 
  Result = left + right;
  System.out.println(left + " + " + right + " = " + Result);
  break;
case 2: 
  Result = left - right;
  System.out.println(left + " - " + right + " = " + Result);
  break;
case 3: 
  Result = left * right;
  System.out.println(left + " * " + right + " = " + Result);
  break;
case 4:
  Result = left / right;
  System.out.println(left + " / " + right + " = " + Result);
}

答案 1 :(得分:0)

(我不确定这是完全正确的,因为我不是真的做Java,但是这里有) 我认为错误是你在switch语句中有double Result;的地方--Java只允许case语句中的defaultswitch。尝试将double Result行放在switch (...行的正上方。另外,我确保case 1/2/3语句下面的所有行都正确缩进 - 它可能只是堆栈交换上的格式,但Result = ...行看起来前面有一个字符(不是确定这是否会产生影响,但最好始终拥有一致的代码。)