This series of programs offer an integrated approach i.e. learning arrays, random numbers, reading from a text file, and Object Orientated Programming (OOP) as single progression from the first example program to the last.
The first one is a one-class program with static methods. It creates two arrays and then prints them out.
Here is the output and below is the code. The first column is from the first array and the second column is from the second array.
The second program uses charAt( ) to isolate the first letter, It also prints the arrays out in reverse order. The output of the first method is at the top and the second method is below that. The code is below the image.
The third program generates random numbers (from 1 to 10 or 1 to 100 or 1 to 1000 etc if you edit the code) and stores them in an array. This program generates 6 random numbers (between 1 and 10 inclusive) and prints them out.
Here is the output with the code below.
The fourth program also generates 6 random numbers and stores them in an array but it uses a UI class and a manager class with all the methods. One of the methods is a private “helper” method – it generates the random number for the exclusive use of the rest of its own class. No parameters are passed in this program.
Here is the output with the code below.
The fifth program is the same as the first one except that it reads in the names of the months from a text file (“months.txt”). We use the Scanner class to assist us to do this. Here NetBeans can assist us with our imports and error trapping (PowerPoint Demonstation). The names of the months are then assigned to the String array for printing out later. Note that because we are not declaring the array literally, we have to tell Java how big the array must be.
private static String[] monthsArray = new String[12]; // 12 elements in this array.
We also do not know how many elements will be in the text file. Therefore we use a while loop and a counter to read in the text file until it reaches the end; the counter is then used to tell us how many elements were read in.
while(scFile.hasNext()){ // loop continues to the end
String line = scFile.nextLine(); // we read in the whole line
monthsArray[counter] = line; // the line is assigned to the next position in the array using “counter”
counter++; // the counter is increased by one
}
Here is the output of the program followed by the code.