数组打印方法 java

arrays print out method java

我尝试编写一个显示数组值的程序,该数组由 2 classes 组成。

其中一个 class 包含一个在循环中使用 System.out.print 的方法:

public class methodsForArray{
int numbers[];

    public void printOutArray(){
        for (int i=0; i<numbers.length; i++){
        System.out.print(numbers[i]);
        }
    }
}

在另一个 class 中应用了此方法 printOutArray():

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

methodsForArray myObject=new methodsForArray();
myObject.numbers[]={1,3,4};
myObject.printOutArray();    //Here i apply the method
     }
}

这种方法适用于显示字符串或整数。但为什么它不适用于数组?我该如何修复该程序?尝试编译 class application1,导致以下错误消息:

application1.java:5: error: not a statement
myObject.numbers[]={1,3,4};
                ^
application1.java:5: error: ';' expected
myObject.numbers[]={1,3,4};
                  ^
application1.java:5: error: not a statement
myObject.numbers[]={1,3,4};
                    ^
application1.java:5: error: ';' expected
myObject.numbers[]={1,3,4};
                     ^
4 errors

谢谢。

您错过的东西很少。

1] 您应该始终定义您的 class 名称,首字母应大写 - 因此它是 MethodsForArray

2] 您已经在 MethodsForArray 中声明了 int numbers,但还没有 initialized/defined。因此,每当您分配价值时,您都应该定义它然后分配价值; 在这种情况下,我分配了匿名数组

myObject.numbers=new int[]{1,3,4};

请在下面找到工作代码示例

public class MainClass{
    public static void main(String[]args){
         MethodsForArray myObject=new MethodsForArray();
         myObject.numbers=new int[]{1,3,4};
         myObject.printOutArray();    //Here i apply the method
     }
}

class MethodsForArray{
    int numbers[];

        public void printOutArray(){
            for (int i=0; i<numbers.length; i++){
                System.out.print(numbers[i]);
            }
        }
}