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

Java Lesson 7: Random Number Generator

Advertisements

Hello everybody,

It’s Michael, and I’ve decided to give you guys another series of java lessons. In this post, I’ll show you how to create your own random number generator, which is a tool that can generate random numbers in Java. Generating random numbers in Java is a common task that is used for a variety of purposes, such as gambling, statistical sampling, and any other scenario where you would need to simulate unpredictable behavior. Random number generators can also be used with arrays, which will be the topic of my next Java post.

Now let’s begin with an example of a simple random number generator:

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
Random generator = new Random ();
int random = generator.nextInt(50);
System.out.println(random);
}
}

 

And here are two sample outputs:

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

run:
12
BUILD SUCCESSFUL (total time: 1 second)

Before writing the code for your program, remember to import java.util.Random (include this package anytime you plan on using the random number generator).

So what does all of this code mean? First of all, the Random generator = new Random () line indicates your random number generator variable. You keep the parentheses empty since you will indicate the boundaries in a separate int variable, which in this case is found in the line int Random = generator.nextInt(50). This line indicates that you want your program to print out a random number between 0 and 50 (the number in the parentheses indicates the upper limit of your random number generator). System.out.println(random) prints out a random number between 0 and 50

But what if you wanted to print out several random numbers? We can do just that, with the help of our random number generator and a handy for-loop:

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
Random generator = new Random ();

for (int i = 0; i <= 8; i++)
{
int random = generator.nextInt(120);
System.out.print(random + ” , “);
}

}
}

And here are two sample outputs:

run:
6 , 17 , 20 , 98 , 82 , 46 , 43 , 5 , 19 , BUILD SUCCESSFUL (total time: 1 second)

run:
65 , 13 , 116 , 16 , 5 , 1 , 6 , 28 , 72 , BUILD SUCCESSFUL (total time: 2 seconds)

I kept the variables the same as the previous example; all I did here was add a for loop (for int = 0; i <= 8; i++) and changed the upper limit to 120. This program will print out 8 random numbers between 0 and 120, each separated by a comma.

So what if you want to use a custom range for your random number generator, as opposed to relying on the default of 0? Here’s how:

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
Random generator = new Random ();

for (int i = 0; i <= 8; i++)
{
int random = 200 + generator.nextInt(600);
System.out.print(random + ” , “);
}

}
}

And here are two sample outputs:

run:
555 , 211 , 587 , 707 , 545 , 653 , 594 , 785 , 520 , BUILD SUCCESSFUL (total time: 2 seconds)

run:
415 , 345 , 579 , 462 , 660 , 695 , 593 , 337 , 505 , BUILD SUCCESSFUL (total time: 2 seconds)

The program is the same as the previous example, save for changing the upper limit to 600 and adding 200 + in front of the generator.nextInt line. Remember how I said I was going to show you how to use a custom range for your random number generator? Well, the 200 + is exactly how you can do that because putting this (or any number for that matter) in front of the generator.nextInt(600) line ensures that the range of your random number generator will only be from 200 to 600.

And last but not least, let’s see what happens when you want to input the value for the upper limit:

package javalessons;
import java.util.Random;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Random generator = new Random ();
Scanner sc = new Scanner (System.in);
System.out.println(“Please choose a number: “);
int custom = sc.nextInt();

for (int i = 0; i <= 8; i++)
{
int random = generator.nextInt(custom);
System.out.print(random + ” , “);
}

}
}

And here are two sample outputs (using 35 for the first example and 91 for the second):

run:
Please choose a number:
35
31 , 23 , 4 , 5 , 22 , 9 , 14 , 11 , 10 , BUILD SUCCESSFUL (total time: 4 seconds)

run:
Please choose a number:
91
78 , 45 , 63 , 82 , 89 , 58 , 12 , 8 , 61 , BUILD SUCCESSFUL (total time: 2 seconds)

In this program, I added a Scanner variable (along with importing the Scanner class) and a custom int variable, which allows you to choose the endpoint for your random number generator (the start-point is still 0). As you can see from each sample output, the program will print out 8 random numbers that are less than or equal to the number that was inputted.

Thanks for reading,

Michael