package javaapplication9; import java.util.Random; /* UsingArrays.java example code AC Chapin */ public class UsingArrays { // given an array of ints, print it out, one per line public static void printList(int[] list) { System.out.println("---LIST---"); for (int i = 0; i < list.length; i++) { System.out.println(list[i]); } System.out.println("----------"); } // given a length and a value // return an array of that length // where all the elements have that value public static int[] makeList(int len, int val) { // won't make an array of size less than 1 if (len < 1) { return null; } // set up the array with the right length int[] list = new int[len]; // fill it with the given value for (int i = 0; i < list.length; i++) { list[i] = val; } return list; } public static void main(String[] args) { // set up a random number generator Random randgen = new Random(); // seed randgen so we get same numbers every time // commented out to try more random numbers //randgen.set(5555); int[] list1 = new int[10]; // fill the array with random ints from -10 to 10 (inclusive for (int i = 0; i < list1.length; i++ ) { list1[i] = randgen.nextInt(21) - 10; // (21) gives a number from 0 to 20 // add or subtract to set the minimum number // -10 gives a number from -10 to 10 } // using an individual element list1[0] = 100; // passing the whole array -- no square braces printList(list1); // use makeList to set up an array of length 10 that's all 5's int [] list2 = makeList(10,5); // then print it printList(list2); // makeList returns an array of length 5 that's all 55's // and printlist prints it printList(makeList(5, 55)); double[] dlist = new double[10]; // fill the array with random doubles from 50 to 150 for (int i = 0; i < dlist.length; i++ ) { dlist[i] = randgen.nextDouble() * 100 +50; // nextDouble gives a number from 0.0 to 1.0 // multiply to set the range: // * 100 gives a number from 0.0 to 100.0 // add or subtract to set the minimum number // +50 gives a number from 50 to 150.0 } } }