arrays print out method java

87 Views Asked by At

I try to write a program that displays the values of an array and that is composed of 2 classes.

One of these classes contains a method that uses System.out.print in a loop:

public class methodsForArray{
int numbers[];

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

In the other class this method printOutArray() is applied:

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
     }
}

This way of doing works to display Strings or integers. But why does it not work for arrays? And how could i fix the program? Trying compile the class application1, results in following error message:

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

Thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

There are few things you missed out.

1] You should always define your class Name such that first letter should be Uppercase - hence it is MethodsForArray

2] You have declared int numbers in MethodsForArray but havent initialized/defined yet. Hence whenever you assign value you should be defining it and then assign value; In this case I have assigned anonymous array

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

Please find working code sample below

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