tags:

views:

29

answers:

2
import java.util.Arrays;
import java.util.*;

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

}
  }

 class List {


private static final int NUMINTS = 10;
public List(int numints) {

    int list[];
    list = new int[NUMINTS];

}

public void fillWithRandom(int list[]) {
 Random r;
 r = new Random();

 int i;

 for(i=0; i < NUMINTS ; i++)
     list[i] = r.nextInt();
} 

public void print(int list[]) {
    int i;
    System.out.println("before sort():");
    for(i=0 ; i < NUMINTS; i++)
        System.out.println(list[i]);

    Arrays.sort(list, 0, NUMINTS);
    System.out.println("--------");
    System.out.println("after sort():");
    for (i = 0 ; i < NUMINTS; i++)
        System.out.println(list[i]);
}
   }

I want to create an array of random numbers. I am not quite sure how to implement the methods from my class List into the Main class. I want main to create the array and then print it out.

+1  A: 

It looks like you're getting confused between an int array and a class you've created called List. Since you seem comfortable passing around int arrays, I would suggest getting rid of the List class (or leaving that as your class and adding a main method there).

In fact, just play around with creating an int[10], populating it with random numbers, and printing it out all in your main method. This will let you test quickly without having to worry about classes, instantiation, and method calling. Then once you have this, abstract each of these operations back out into methods, and play around with calling methods from main.

If a method is not static, then you can't call it directly from a static method (main), unless you call it on an instance of the class. For example, you can't call List.print(int[]) because it's not static, so you'd have to create a List object, and then call print(int[]) on that object.

tl;dr I'm trying to give some hints/advice, since this looks a lot like a homework problem.

Ben Taitelbaum
A: 

One problem in your code is that you are not using the argument passed,

    public List(int numints) { // numints never used, hence useless
       int list[];
       list = new int[NUMINTS];  // list is a local variable. It has no scope outside this 
                                 // method and the method also doesn't have any side-effect    
    }

Now, come to the point, how you can call methods of List class in your Main class's main() method.

public static void main(String[] args) {
    List list = new List(10);
    int[] intArr = new intArr[10];

    list.fillWithRandom(intArr);
    list.print(intArr);
}

Few suggestions,

  1. Its better to declare array type like this int[] arr; instead of int arr[]
  2. If you must use 2 classes, then it seems you should have a int[] intArr; in your List class. So, you need not pass intArr back or forth
  3. Initialise the array using the arguments received, not with the NUMINTS
Adeel Ansari