Computer Science 210
Data Structures
Fall 2017, Siena College
ArrayFun BlueJ Project
Click here to download a BlueJ project for ArrayFun.
ArrayFun Source Code
The Java source code for ArrayFun is below. Click on a file name to download it.
/** * A program to develop in class to review and experiment with * arrays. * * @author Jim Teresco and the Siena College CSIS 210 Fall 2017 Class */ import java.util.Random; import java.util.Scanner; public class ArrayFun { public static void main(String args[]) { // declare an array with some ints // use a static initialization, which will allocate // space for the given number of ints and initialize them int static_a[] = { 23, 51, 1, 99, 49, 2, 10, 21, 17, 13 }; // create our keyboard input Scanner Scanner keyboard = new Scanner(System.in); // prompt for and read values System.out.println("How many numbers? "); int count = keyboard.nextInt(); System.out.println("Lower and upper bounds? "); int low = keyboard.nextInt(); int high = keyboard.nextInt(); keyboard.close(); // declare and construct array int a[] = new int[count]; // construct my Random object Random r = new Random(); // loop to fill in array values for (int i = 0; i < a.length; i++) { a[i] = r.nextInt(high - low + 1) + low; } // print out our array, being sure to use the // array's length for our upper bound for (int i = 0; i < a.length; i++) { System.out.println("a[" + i + "] = " + a[i]); } // sequential search for largest and smallest int largest = a[0]; int smallest = a[0]; int largeIndex = 0; int smallIndex = 0; // search remaining items for smaller/larger values for (int i = 1; i < a.length; i++) { if (a[i] > largest) { largest = a[i]; largeIndex = i; } if (a[i] < smallest) { smallest = a[i]; smallIndex = i; } } System.out.println("smallest is : " + smallest + " at a[" + smallIndex + "]"); System.out.println("largest is : " + largest + " at a[" + largeIndex + "]"); } }