【问题标题】:error when calling main method with parameters带参数调用main方法时出错
【发布时间】:2019-12-25 05:05:14
【问题描述】:

我有以下代码:

public class classroom{
public static void main(Integer[] args) {
    int teachers = args[0];
    int students = args[1];
    int desks = args[2];
    int computers = args[3];
    double ratio = students/desks;
    if (teachers == 1) {
           if (computers >= students) {
               if (ratio <= 6) {
                   System.out.println("this classroom is vald");
                }
            }
        }
        else {
            System.out.println("this classroom is not valid");
        }
    }
}

我将代码作为教室.main(1,2,3,4) 运行,java 返回以下错误:'identifier expected'。知道我应该如何解决这个问题吗?

【问题讨论】:

  • 你是什么意思“我运行代码作为教室.main(1,2,3,4)”?你是怎样做的?此外,就显示教室是否“有效”而言,您的逻辑似乎是错误的。并进行整数数学以启动。
  • 您的代码对我有用。您确定您发布了您尝试运行的内容吗?你在哪一行得到错误?

标签: java


【解决方案1】:

你应该解决这个问题调用方法为:

Classroom.main(new Integer[]{1, 2, 3, 4});

【讨论】:

    【解决方案2】:

    我认为您需要... 运算符,调用Classroom.main(1, 2, 3, 4) 将需要您使用三个点运算符更改方法参数。通过使用三点运算符...,您可以传递整数参数而无需显式创建数组。

    public class ClassRoom {
        public static void main(String[] args) {
            ClassRoom.main(1, 2, 3, 4);
        }
        private static void main(Integer... args) {
            for (Integer i : args) {
                System.out.println("Argument [ " + i + " ] = " + args[i-1]);
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      您应该通过classroom.main(new Integer[] { 1, 2, 3, 4 })而不是classroom.main(1, 2, 3, 4)调用该函数。
      因为函数声明为classroom.main(Integer[] args),而不是classroom.main(int a, int b, int c, int d)

      另一个建议:Java 类名应该使用 Camel Case 作为 Java 命名约定。

      【讨论】:

      • 您好,欢迎来到 Stack Overflow。请不要用签名装饰您的帖子;您已经在每次提交下方获得了一张用户卡,其中包含指向您的个人资料的链接。另见how not to be a spammer.
      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      相关资源
      最近更新 更多