1

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

}
}
3
  • 6
    You can't have a method (printArray) within another method (main). Commented Jan 16, 2013 at 21:10
  • 3
    Always in life, not just here on Stackoverflow, give the error message to the people that you ask for help. Messages are there for a reason. Commented Jan 16, 2013 at 21:12
  • Printing an array like this is a good way to learn Java. Later on, you can just print Arrays.toString(array); Commented Jan 16, 2013 at 21:33

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.