Java Program Demo 2: Arrays, Random Numbers, Inheritance & Polymorphism

Advertisements

Hello everybody,

It’s Michael, and today’s post will be my second Java program demo. I will focus on the topics of the last 3 posts (random number generators, arrays, inheritance, and polymorphism); however I may also utilize concepts from the first six Java lessons (such as for loops and if statements) since Java concepts build on each other.

In this demo, I will create three programs that demonstrate the concepts from Java Lessons 7-9 (with some concepts from Lessons 1-6 as well).

Here is my first program:

package programdemo2;
import java.util.Random;

public class ProgramDemo2
{
public static void main(String[] args)
{
String [] maleNames = {“Alex”, “Brian”, “Chester”, “David”, “Eric”, “Felipe”, “Gabriel”,
“Henry”, “Ike”, “Jacob”, “Kyle”, “Lenny”, “Michael”, “Nicholas”,
“Oliver”, “Phillip”, “Quentin”, “Ricky”, “Steven”, “Todd”,
“Ulises”, “Victor”, “William”, “Xavier”, “Yancy”, “Zach”};

Random gen = new Random ();
int limit = gen.nextInt(25);

System.out.println (maleNames[limit]);
}

}

This program demonstrates a simple one-dimensional array along with a random number generator. The array shown above is a String array containing random males names for all 26 letters of the alphabet (and yes Yancy is an actual male name). The random number generator’s upper limit is set to 25, since there are 26 elements (remember the “indexes start at 0” rule). The system will print out any one of the 26 names mentioned (at random). Let’s check out two sample outputs:

run:
Jacob
BUILD SUCCESSFUL (total time: 2 seconds)

run:
William
BUILD SUCCESSFUL (total time: 0 seconds)

Our two sample outputs-Jacob and William-correspond to indexes 9 and 22, respectively (or the 10th and 23rd elements in the array).

Now let’s demonstrate a two-dimensional array:

package programdemo2;
import java.util.Scanner;

public class ProgramDemo2
{

public static void main(String[] args)
{
Scanner s = new Scanner (System.in);
System.out.println(“Pick a number: “);
int num = s.nextInt();

int [][] multiples = new int [5][5];

for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
multiples[i][j] = num*(i+1);
}

}

System.out.println (multiples[4][4]);
}
}

Using a combination of a Scanner, a for-loop, and a two-dimensional array, this program will create a two-dimensional five-by-five array based on the number you input into the Scanner. The five rows will contain five different numbers, while the five columns will contain the same number through the column. The number in a column is calculated using the formula num*(I+1), which means that the number inputted into the Scanner will be multiplied by I+1 in order to figure out what number goes into the column. Remember that I increments by one after each loop iteration, so when the loop starts at 0, the number inputted will be multiplied by 1 (since I+0 would be 1). Likewise, on the final iteration of the loop (I=4), the inputted number will be multiplied by 5, since 4+1=5.

Let’s create a sample array, using 4 different outputs (and using 6 as the Scanner number each time):

run:
Pick a number:
6
30
BUILD SUCCESSFUL (total time: 5 seconds) index[4][2]

run:
Pick a number:
6
24
BUILD SUCCESSFUL (total time: 5 seconds) index[3][3]

run:
Pick a number:
6
24
BUILD SUCCESSFUL (total time: 2 seconds)index[3][0]

run:
Pick a number:
6
12
BUILD SUCCESSFUL (total time: 6 seconds)index[1][2]

In each of these four outputs, I use a different index but the same Scanner number-6. The indexes to which these outputs correspond are mentioned to the right of the BUILD SUCCESSFUL line.

Here’s a visualization of the array with the outputs filled in. With the information given in the program and outputs, could you fill in the missing elements?

Screen Shot 2019-05-01 at 5.08.40 PM

My last program demo will involve polymorphism and inheritance. Here is my main class (the one from which I will run the program):

import java.util.Scanner;

public class ProgramDemo
{
public static void main (String[]args)
{
Scanner s = new Scanner (System.in);
System.out.println(“Pick a number: “);
double num = s.nextDouble();

String [] time = {“hours”, “days”, “weeks”, “months”};

System.out.println(“Pick an index from 0-3:”);
int index = s.nextInt();

if (index == 0)
{
Days d = new Days();
d.measure(num);
}

else if (index == 1)
{
Weeks w = new Weeks ();
w.measure(num);
}

else if (index == 2)
{
Months m = new Months ();
m.measure(num);
}

else if (index == 3)
{
Years y = new Years ();
y.measure(num);
}

else
{
System.out.println(“Pick another number”);
}
}
}

Now here’s my superclass (which is NOT the same as my main class):

public class TimeMeasurements extends ProgramDemo
{
public void measure ()
{
double num = 0;
System.out.println(num);
}
}

And here are my four subclasses:

public class Days extends TimeMeasurements
{
public void measure(double num)
{
System.out.println(“Number of days is: ” +num/24);
}
}

public class Weeks extends TimeMeasurements
{
public void measure (double num)
{
System.out.println (“Number of weeks is: ” + num/7);
}
}

public class Months extends TimeMeasurements
{
public void measure (double num)
{
System.out.println (“Number of months is: ” + num/4);
}
}

public class Years extends TimeMeasurements
{
public void measure (double num)
{
System.out.println (“Number of years is: ” +num/12);
}
}

Before I get into sample outputs, let me explain the structure of my program.

The first line of the main program in the main method creates a Scanner object, which I will use to store the double variable num. After the line asking the user for input, there is a String array called time, which contains four elements-hours, days, weeks, and months. The user is then asked to choose a number from 0-3 (corresponding to each of the possible indexes), and based on the input, one of the four if statements will execute. OK, there’s also an else statement, but that will only execute if the number you pick for the Pick an index from 0-3:  line is not between 0 and 3 (or any decimals for that matter).

The superclass TimeMeasurements extends the main class ProgramDemo; this means that TimeMeasurements inherits all variables and methods of the ProgramDemo class. This extension ultimately doesn’t mean much since the only method in ProgramDemo is the default main method; however, the num variable from ProgramDemo does carry over.

Here is where polymorphism comes in. In TimeMeasurements, there is a method called measure which converts a number from one unit of time to another. This method is of type void-meaning it doesn’t have a return statement-but its parameter is double num, which is the exact same variable and type as the double num in my main class. Each of my four subclasses-Days, Weeks, Months, and Years-also contains the measure method, but each class will return a different result for the same method. Days divides num by 24 since I’m converting from hours to days. Weeks divides num by 7, Months divides num by 4, and Years divides num by 12. The polymorphism is present throughout the measure method in my superclass and subclasses since the calculations in each method differ from class to class (and the TimeMeasurements class simply sets the num to 0).

  • My subclasses extends the superclass TimeMeasurements, which in turn extends the main class ProgramDemo. So in turn, my 4 subclasses extend ProgramDemo
    • This is why I chose to use num as the variable for all 4 subclasses and TimeMeasurements; using num would allow the program to produce output based on the formulas specified in each of the subclasses measure methods.
  • I used double for num because chances are high that the program’s calculations will involve decimals.
  • A method’s parameters and type don’t have to be the same. Case in point-the measure method; this method is of type void but the parameter is of type double.

There are 4 if statements and an else statement in this program, which will do the following based on the Pick an index input:

  • If 0 is chosen, an object of class Day will be created and the measure method for class Day will be executed. The output will show you how many days are in X amount of hours (X being your num input).
  • If 1 is chosen, an object of class Week will be created and the measure method for class Week will be executed. The output will show you how many weeks are in X days.
  • If 2 is chosen, an object of class Month will be created and the measure method for class Month will be executed. The output will show you how many months are in X weeks.
  • If 3 is chosen, an object of class Year will be created and the measure method for class Year will be executed. The output will show you how many years are in X months.
  • If neither 0, 1, 2, or 3 is chosen, the else statement will execute, which will simply display the line Pick another number.

Now let’s show five sample outputs (to account for the 5 possible conditions). For the outputs, I’ll go in order of conditional statements (in other words, I’ll start with 0):

run:
Pick a number:
65
Pick an index from 0-3:
0
Number of days is: 2.7083333333333335
BUILD SUCCESSFUL (total time: 49 seconds)

In this output, I chose index 0 and the number 65-referring to 65 hours. The numerical output was 2.71 (rounded to 2 decimal places), meaning that there are approximately 2.71 days in 65 hours.

Next I’ll choose index 1:

run:
Pick a number:
112
Pick an index from 0-3:
1
Number of weeks is: 16.0
BUILD SUCCESSFUL (total time: 13 seconds)

I chose 112 as my num input-referring to 112 days. I got 16 as the output, which means that 112 days equals 16 weeks.

Now I’ll use index 2:

run:
Pick a number:
88
Pick an index from 0-3:
2
Number of months is: 22.0
BUILD SUCCESSFUL (total time: 23 seconds)

I chose 88 as my num input-referring to 88 weeks. I got 22 as the output, which means that 88 weeks equals 22 months.

Now time to try index 3:

run:
Pick a number:
105
Pick an index from 0-3:
3
Number of years is: 8.75
BUILD SUCCESSFUL (total time: 10 seconds)

And last but not least, let’s enter a number other than 0, 1, 2, or 3:

run:
Pick a number:
35
Pick an index from 0-3:
5
Pick another number
BUILD SUCCESSFUL (total time: 8 seconds)

I picked 35 as my number and 5 as my index and, since my chosen index wasn’t 0, 1, 2, or 3, I got the message Pick another number as my output.

Thanks for reading,

Michael

Leave a ReplyCancel reply