为什么我们不能在Java的main方法中实现一个方法? [英] Why can't we implement a method inside the main method in Java?
本文介绍了为什么我们不能在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
方法中定义方法.
You can't define a method within another method in Java. In particular, you can't define a method within the main
method.
对于您而言,您可以这样写:
In your case, you could write:
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的main方法中实现一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文