为什么我们不能在Java中的main方法中实现一个方法?

为什么这不起作用?

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]); } } } 

您无法在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]); } } 

好吧,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(); } } 

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

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

因为Java语言规范不允许它。

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

在java中,您必须将方法分开。 :/抱歉