-4

为什么这不起作用?

public class AddArray
{
    public static void main(String[] args) 
    {

        int[] x = {1,2,3};
        int[] y = {1,2,3};

        dd(x,y);

        public static void add(int[]a, int[]b)
        {
            int[] sum = new int[a.length];
            for (int i=0; i<a.length; i++)
                sum[i] = a[i] + b[i];
            for (int i=0; i<a.length; i++)
                System.out.println(sum[i]);
        }
    }
}
4

5 回答 5

8

您不能在 Java 中的另一个方法中定义一个方法。特别是,您不能在方法中定义main方法。

在你的情况下,你可以写:

public class AddArray {

    public static void main(String[] args) {

        int[] x = {1,2,3};
        int[] y = {1,2,3};

        add (x,y);
    }

    private static void add (int[] a, int[] b) {
        int[] sum = new int[a.length];
        for (int i = 0; i < a.length; i++)
            sum[i] = a[i] + b[i];
        for (int i = 0; i < a.length; i++)
            System.out.println(sum[i]);
    }
}
于 2012-09-22T20:34:25.443 回答
4

好吧,Java 不支持嵌套函数。但问题是你为什么需要那个?如果你真的有需要嵌套方法的情况,那么你可以使用local class.

它看起来像这样: -

public class Outer {
    public void methodA() {
         int someVar = 5;

         class LocalClass {
              public void methodB() {
                   /* This can satisfy your need of nested method */
              }
         }

         // You cannot do this instantiation before the declaration of class
         // This is due to sequential execution of your method..

         LocalClass lclassOb = new LocalClass();
         lclassOb.methodB();
    }
}

但是,您必须注意,您的本地类仅在其定义的范围内可见。它不能有修饰符:private、、publicstatic

于 2012-09-22T20:51:29.193 回答
2

方法不能在 Java 的其他方法中定义。为了编译你的add方法,必须从main方法中提取出来。

于 2012-09-22T20:35:16.877 回答
1

因为 Java 语言规范不允许这样做。

方法直接属于一个类,不能嵌套。

于 2012-09-22T20:35:28.287 回答
0

在java中,您必须将方法分开。:/ 对不起

于 2012-09-22T20:36:01.663 回答