【问题标题】:Illegal start of expression with method declaration带有方法声明的非法表达式开头
【发布时间】:2019-07-01 14:10:57
【问题描述】:

使用 javac 编译这个简单的代码,它给了我以下错误

Test3.java:38: 错误:表达式的非法开始

公共静态 int minFun (int a, int b) {

我尝试在 main 之外声明变量(即 public static int a、b、c),但没有任何改变。

这让我感到困惑,因为我关注 this tutorial 并使用了一个非常相似的示例代码。

提前感谢您的帮助。

  // Program to output the minimum of two integer numbers

  import java.io.*;

  public class Test3 {

  public static void main (String args[]) {

          int a, b, c;
          String rA, rB;

          InputStreamReader input = new InputStreamReader (System.in);
          BufferedReader keyboard = new BufferedReader (input);

          System.out.println ("Please, enter two integer numbers.");
          try {
                  rA = keyboard.readLine ();
                  a = Integer.parseInt (rA);
                  rB = keyboard.readLine ();
                  b = Integer.parseInt (rB);
          }
          catch (IOException e) {
                  System.err.println ("Not a proper integer number.");
          }
          catch (NumberFormatException e) {
                  System.err.println ("Not a proper integer number.");
          }

          c = minFun (a, b);

          if (a != b) {
                  System.out.println ("The smaller number is " + c);
          }
          else {
                  System.out.println ("The two numbers are equals.");
  }

  public static int minFun (int a, int b) {

          int min;

          if (a < b) {
                  min = a;
          }
          else {
                  min = b;
          }
          return min;
  }
  }

【问题讨论】:

  • main 的最后一个 else 缺少右大括号。
  • 方法签名之前的最后一个大括号是关闭 else 块而不是 main 方法的那个。在它之后添加一个...
  • Ffs 就是这么简单,抱歉浪费了大家的时间
  • 并跟进这两个 cmets:出现问题的原因是,如果没有那个大括号,else 之后的未缩进大括号只会关闭那个 else 子句——但是让您保持在main 函数内。这意味着 public static int minFunctionmain 函数中的一行,这是不允许的。您不能在 Java 中的另一个函数中定义一个函数。

标签: java


【解决方案1】:
      if (a != b) {
              System.out.println ("The smaller number is " + c);
      }
      else {
              System.out.println ("The two numbers are equals.");
      } // <----- was not present

此行缺少花括号。

【讨论】:

  • Stack Overflow 的目标是创建一个每个人都可以从中受益的问题和答案库。由印刷错误引起的问题不太可能帮助其他任何人。这就是为什么它们应该被关闭,而不是回答。 (而且它们通常会在一段时间后被删除,因此首先回答它们会浪费时间。)
  • 确实如此。答案仍然有效(投票赞成答案,投票结束问题)。
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2018-08-16
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 2021-09-22
相关资源
最近更新 更多