Computer Science Canada

Arrays

Author:  BoXxI2004 [ Mon Mar 08, 2004 12:02 am ]
Post subject:  Arrays

in an array how would u create an random array, ask the user to input some number they can be any like 14 , 25 .. and how would u store them?

Author:  wtd [ Mon Mar 08, 2004 1:53 am ]
Post subject: 

As array of random numbers, or an array of random length?

Author:  BoXxI2004 [ Mon Mar 08, 2004 7:05 am ]
Post subject: 

well the user inputs the length he wants... and radom numbers (in a range) are created in the array

Author:  Tony [ Mon Mar 08, 2004 11:17 am ]
Post subject: 

so you would just use a forloop to fill in the array Confused
code:

for (int i=0;i<yourArray.length();i++)
{
     yourArray[i] = //generate random value here
}


For the random value, you got to include somethign like .util.Random; and then initialize your randNum class or what not Thinking I'm not sure

Author:  Dan [ Mon Mar 08, 2004 11:22 am ]
Post subject: 

BoXxI2004-> plz make you avtare smaller, it mess with frame on small rez comps.

Author:  wtd [ Mon Mar 08, 2004 4:29 pm ]
Post subject: 

Hmmm... not tested:

code:
import java.lang.*;
import java.io.*;
import java.util.Random;

public class Test
{
   private static int desiredLength;

   public static int[] intArrayOfLength(int length)
   {
      return new int[length];
   }

   public static void promptForRandomLength(PrintStream output = System.out) throws IOException
   {
      output.print("Please input a random length: ");
   }

   public static void readRandomLength(InputStream input = System.in) throws IOException
   {
      BufferedReader in = new BufferedReader(new InputStreamReader(input));
      desiredLength = Integer.parseInt(in.readLine());
   }

   public static int[] intArrayOfDesiredLength()
   {
      return intArrayOfLength(desiredLength);
   }

   public static void populateIntArrayWithRandomValues(int[] arr)
   {
      Random randNum = new Random(System.currentTimeMillis());
      for (int i = 0; i <arr.length; i++)
          arr[i] = randNum.nextInt();
   }

   public static void main(String[] args)
   {
      int[] myArray;
      promptForRandomLength();
      readRandomLength();
      myArray = intArrayOfDesiredLength();
      populateIntArrayWithRandomValues(myArray);
   }
}


: