user1050619
user1050619

Reputation: 20856

Java printing array error

Im a newbie to Java and wrote this class to try few array options..can you please what is the error in the method printarray..Eclipse points me a error but im unable to debug

public class arrarytest {
public static void main(String args[]){
    int[] x = {1,2,3,4};
    for(int y:x){
        System.out.println(y);
    }
    double[] mylist = {1.9,2.9,3.9,4.9};

    for (int i =0; i<mylist.length; i++){
        System.out.println(mylist[i]);
    }

    double total = 0;
    for (int i =0; i < mylist.length; i++){
        total +=mylist[i];
    }
    System.out.println("Total is="+ total);

    public static void printArray(int[] array) {
          for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
          }
        }

}
}

Upvotes: 1

Views: 334

Answers (2)

MrSmith42
MrSmith42

Reputation: 10151

Formatted and corrected some brackets:

public static void main(final String args[]) {
    final int[] x = { 1, 2, 3, 4 };
    for (final int y : x) {
        System.out.println(y);
    }
    final double[] mylist = { 1.9, 2.9, 3.9, 4.9 };

    for (int i = 0; i < mylist.length; i++) {
        System.out.println(mylist[i]);
    }

    double total = 0;
    for (int i = 0; i < mylist.length; i++) {
        total += mylist[i];
    }
    System.out.println("Total is=" + total);
}

public static void printArray(final int[] array) {
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i] + " ");
    }
}

Output:

1
2
3
4
1.9
2.9
3.9
4.9
Total is=13.6

Upvotes: 1

kosa
kosa

Reputation: 66637

You haven't specified what is the error eclipse displaying, but one issue seems to be:

 public static void printArray(int[] array) {
          for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
          }
        }

You have above method inside main method. Move it outside main method.

Upvotes: 2

Related Questions