Java Lesson 13: Recursion

Hello everybody,

It’s Michael, and today’s Java lesson will be on recursion.

What is recursion? In the context of Java programming, recursion is whenever a program has a subtask that’s a smaller version of the entire program’s task. To keep things simple, I will mostly talk about recursion as it relates to recursive methods, which are methods that call themselves.

You might be thinking “How can a method call itself?” The answer would be with a recursive call, which is a method’s prompt to call itself.

Now let’s demonstrate recursive methods with a simple example:

package javalesson13;

public class JavaLesson13
{

public static void main(String[] args)
{
increasedouble(19);
}

public static void increasedouble (int num)
{
if (num >= 200)
{
System.out.println();
}

else
{
System.out.println(num);
increasedouble(num * 2);
}
}

}

And here’s the output:

run:
19
38
76
152

BUILD SUCCESSFUL (total time: 0 seconds)

This program is a rather simple example of recursion; in this example, I pass a number into the increasedouble method. The number will keep doubling so long as each successive result is less than 200. Once the closest possible number to 200 is reached, the program will run the System.out.println() command and then stop running. The line (if num >= 200)-if the number obtained is greater than or equal to 200-functions as a base case, which is the condition that needs to be reached to stop recursion.

  • I know increasedouble isn’t the best possible method name, but I couldn’t use double as a method name because that is a reserved word, which are words that can’t be used in variable, object, class, or method names since they are already part of Java syntax (sorry I didn’t mention this earlier)

OK, so you might be thinking that this program could have been written with a simple while or do-while loop. Writing this program with a loop would certainly work, and would be the preferred way of solving this particular programming problem. However, I wanted to demonstrate recursion by starting off with a simple example; plus, there are cases where recursion will work better than loops.

Here’s a more complex example of recursion:

public class JavaLesson13
{

public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println(“Please pick a number: “);
int num = s.nextInt();
System.out.println(“The month is ” + returnMonth(num));
}

public static String returnMonth (int num2)
{
String month = null;

switch(num2)
{
case 1: month = “January”; break;
case 2: month = “February”; break;
case 3: month = “March”; break;
case 4: month = “April”; break;
case 5: month = “May”; break;
case 6: month = “June”; break;
case 7: month = “July”; break;
case 8: month = “August”; break;
case 9: month = “September”; break;
case 10: month = “October”; break;
case 11: month = “November”; break;
case 12: month = “December”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}

}
return month;
}
}

And here’s some sample output:

run:
Please pick a number:
11
The month is November
BUILD SUCCESSFUL (total time: 6 seconds)

In this program, the user inputs a number and the message The month is along with the corresponding month for that number will be displayed–IF the number entered is between 1 and 12. I return the correct month by calling the returnMonth

Here’s where I introduce two new Java terms-switch and case. Switch statements have similar logic to if-else statements, but unlike if-else statements, switch statements allow for multiple scenarios.

  • OK, if statements with multiple instances of else if can handle multiple scenarios as well. However, having a switch statement with multiple instances of case makes if-else if-else statements unnecessary. Plus switch statements are easier to read and understand-but that’s just my opinion.

As you can see in the example above, switch statements have several instances of case. Case statements detail all possible scenarios for a program along with a default case (using the reserved word default). The code in the default case will run if none of the other cases are true.

In this case, the default case will run if the number inputted isn’t between 1 and 12. All that will happen in the default case is that the word ERROR will be displayed and the program will stop running (as denoted by the System.exit(0) line).  However, if the number inputted is between 1 and 12, then one of the twelve case statements will be executed depending on the user’s input.

  • Think of the default statement as the else in an if-else if-else code block, since the else statement will execute if neither the if nor the else if statements are true, just as the default statement will execute if none of the other case statements are true.

Notice how all of the case statements (not including the default statement) end with break. This is because break will end the program once the correct case is found and the correct output is returned. Plus, if I didn’t have any break statements, the program could possibly run infinitely (though this is just my theory).

Now here’s a sample output that will run the default case:

run:
Please pick a number:
22
ERROR
BUILD SUCCESSFUL (total time: 6 seconds)

One more thing I wanted to note about recursion is that, even though the above example used numbers as cases, you can use other data  types for cases as well (such as booleans and Strings).

Here’s an example of using Strings in case statements, which simply does the opposite of the previous example program (ask for the month and print the corresponding number):

package javalesson13;
import java.util.Scanner;

public class JavaLesson13
{

public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println(“Please pick a month: “);
String month = s.nextLine();
System.out.println(“The number is ” + returnNumber(month));
}

public static int returnNumber (String month)
{
int num = 0;

switch(month)
{
case “January”: num = 1; break;
case “February”: num = 2; break;
case “March”: num = 3; break;
case “April”: num = 4; break;
case “May”: num = 5; break;
case “June”: num = 6; break;
case “July”: num = 7; break;
case “August”: num = 8; break;
case “September”: num = 9; break;
case “October”: num = 10; break;
case “November”: num = 11; break;
case “December”: num = 12; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}

}
return num;
}
}

And here’s some sample output using the current month-November:

run:
Please pick a month:
November
The number is 11
BUILD SUCCESSFUL (total time: 2 seconds)

Here are the tweaks I made to the previous program:

  • Swapped the return and parameter types of the returnMonth method-in the previous example, the returnMonth method returned a String but took an int as a parameter. In this example, the opposite is true.
  • Changed all of the cases to the names of the months and the return values to int
  • The returnMonth method now returns an int rather than a String

Other than those three changes, the program logic is still the same. Break is still found after each case statement, and the default statement will still print out ERROR and exit the program.

Also know that if you try inputting a number in this program, you will get ERROR, as shown below:

run:
Please pick a month:
7
ERROR
BUILD SUCCESSFUL (total time: 4 seconds)

Thanks for reading,

Michael

Java Lesson 12: Try-Catch & Exception Handling

Hello everybody,

It’s Michael, and today’s Java lesson will be on try-catch statements and exception handling in Java.

In Java lingo, exceptions are errors that occur in the program, which can be caused by coding errors made by the programmer, errors caused by incorrect input (in programs that utilize user input), or other unforeseeable things. When errors occur, Java will generate an error message-the technical term for this is throwing an exception.

Now let’s demonstrate errors in action. Consider the following program:

public class TryCatch
{
public static void main (String [] args)
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}
}

And here’s the error message we get when we try to run this code:

run:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 11
at JavaLesson12.TryCatch.main(TryCatch.java:17)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

In this example, we get an ArrayIndexOutOfBoundsException when we try to run the code. This is just one of the many types of exceptions you might run into.

We get this particular exception because we are trying to retrieve an array index that doesn’t exist. Since there are only 9 elements in this array, the highest index we can use is 8.

Now, let’s fix this program using a try-catch statement:

public class TryCatch
{
public static void main (String [] args)
{
try
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}

catch (Exception e)
{
System.out.println(“Index out of bounds!”);
}
}
}

And here’s the output:

run:
Index out of bounds!
BUILD SUCCESSFUL (total time: 0 seconds)

So what exactly does the try-catch statement do? This statement (or rather statement pair) tries to catch an error (or exception) and, should an error be found, executes the block of code in the catch statement. In this case, an error is found, so the code in the catch statement is executed (the only thing that happens here is that Index out of bounds! is printed).

  • Never have a try statement without a corresponding catch statement!
  • The catch statement will always have Exception e as a parameter (though I’m not sure why).

You can also use the word finally after a try-catch statement. All this does is execute code after a try-catch statement is finished running (regardless of whether or not an error is found). Here’s an example:

public class TryCatch
{
public static void main (String [] args)
{
try
{
int [] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(numbers[11]);
}

catch (Exception e)
{
System.out.println(“Index out of bounds!”);
}

finally
{
System.out.println(“All done here”);
}
}
}

And here’s the output:

run:
Index out of bounds!
All done here
BUILD SUCCESSFUL (total time: 1 second)

There are basically no changes in the way the program runs-an error is found, so Index out of bounds! is printed. The only difference between this program and the one in the previous example is that the message All done here is printed after the try-catch statement is finished running. This happens because All done here is the block of code that corresponds to the finally statement.

  • Finally statements will ALWAYS go after try-catch statements!

The last thing I wanted to discuss in this post is the throw statement. In Java, throw works similar to try-catch statements, except it allows you to create a custom error. Throw is always used with a Java exception type.

Here’s a sample program with throw (it’s not the same one from the previous examples):

import java.util.Scanner;

public class TryCatch
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
int a, b, quotient;

System.out.println(“Please pick a number: “);
a = sc.nextInt();

System.out.println(“Pick another number: “);
b = sc.nextInt();

quotient = a/b;

if (b == 0)
{
throw new ArithmeticException (“Can’t divide by 0”);
}

else
{
System.out.println(“The quotient is: ” + quotient);
}
}
}

And here’s the output with b as 0:

run:
Please pick a number:
11
Pick another number:
0
Exception in thread “main” java.lang.ArithmeticException: / by zero
at JavaLesson12.TryCatch.main(TryCatch.java:27)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)

Here’s the output with b not being 0:

run:
Please pick a number:
15
Pick another number:
5
The quotient is: 3
BUILD SUCCESSFUL (total time: 3 seconds)

In this program, I have a Scanner object and three int variables-a, b, and quotient (which equals a/b). After I set up the Scanner object, I ask the user to pick two numbers-the first number will be equal to a and the second number to b. I then divide a by b and store the result in the quotient variable.

An ArithmeticException will be thrown if b equals 0, since you can’t divide anything by 0. In the first example, I set b to 0 and my program threw an ArithmeticException. However in my second example, I set b to 3 and instead got the message The quotient is: 3.

  • Throw statements are often used with custom methods, but those aren’t always necessary (after all, I didn’t use a custom method in this example). For more on custom methods, please read my previous post Java Lesson 11: Method Making.
  • There are at least a good 150 exception types in Java, so there’s no need to memorize them all. Here’s a handy guide to the various exception types in Java. Click on an exception type to learn more about it.

Thanks for reading,

Michael

Java Lesson 11: Method Making

Welcome back loyal readers,

I’m back after a 34-day hiatus and ready to post more amazing content. This lesson will be on method making in Java, in other words, I will teach you how to create you own methods in Java.

Now, I know I covered method creation in the previous lesson on encapsulation. However, the methods I discussed were simply getter and setter methods; in this lesson, I will discuss how to create any type of method.

Here’s the basic syntax of a method:

    • public/private/protected [return type] method Name (parameter 1, parameter 2 …)

Now, what does this mean? Let me explain:

  • You would usually put public, private, or protected as the first part of the method. These three words serve as access modifiers, which denote which parts of the program can access the method. Here’s a better explanation on each:
    • public-any class in the program can access the method
    • private-only the class where the method is located can access the method
    • protected-the class where the method is located can access the method, but so can any classes in the same package as well as any subclasses of that class can also access that method (don’t worry I’ll demonstrate this later in this post)
  • A return type indicates what type of variable you want to return. The possible return types are the same as the the possible variable types (String, int etc.). However, keep these three things in mind regarding return types:
    • You can only return one item per method.
    • If you don’t want your method to return anything, simply use the word void as the return type.
    • Remember to write a line of code with return [variable name]
  • The method name is honestly pretty self-explanatory.
  • Inside the parentheses, you would put any parameters (variables inside the method) you wish to use-or you could use no parameters if you want. If you want to use multiple parameters, separate each individual parameter with a comma.

Now, let’s demonstrate some method making:

First, here’s our method class-this is the term I will use to describe any class where individual methods are made (not including the main method):

public class ProgramDemo
{
public int add (int a, int b)
{
return a+b;
}

public int subtract (int c, int d)
{
return d-c;
}

public int multiply (int e, int f)
{
return e*f;
}

public double divide (double g, double h)
{
return g/h;
}

public double square (int i)
{
return Math.pow(2, i);
}

public double log10 (double j)
{
return Math.log10(j);
}
}

And here’s our main class-this is the class which has the main method from which we will run this program:

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
System.out.println(math.add(45, 19));
System.out.println(math.subtract(18, 22));
System.out.println(math.multiply(36, 11));
System.out.println(math.divide(13.4, 2.3));
System.out.println(math.square(15));
System.out.println(math.log10(23));
}
}

And here’s the output:

64
4
396
5.82608695652174
32768.0
1.3617278360175928
BUILD SUCCESSFUL (total time: 0 seconds)

The class ProgramDemo is the method class since it has the methods that we will use for the program. The Arithmetic class is the main class since it has the main method, and it is the class from where we will run the program.

Notice how none of the ProgramDemo methods are void; all of the methods in that class have a return type, whether int or double.

In the main class-Arithmetic-I was able to access all of the methods of the ProgramDemo class simply by creating an object of the ProgramDemo class-math. There was no need to use extends here, as the methods are public and thus accessible by the entire program.

After I created the math object, I called all six of its methods, filled in each of the parameters for each method, and used System.out.println to print out the results of each calculation.

  • If you forgot what a logarithm is, here’s a simple explanation:
    • Screen Shot 2019-10-03 at 8.43.37 PM
    • For instance, the base 10 logarithm of 1000 would be 3, as 10 to the power of 3 equals 1000.

But what if our methods were private? Let’s demonstrate by first showing the ProgramDemo class with all of the private methods:

public class ProgramDemo
{
private int add (int a, int b)
{
return a+b;
}

private int subtract (int c, int d)
{
return d-c;
}

private int multiply (int e, int f)
{
return e*f;
}

private double divide (double g, double h)
{
return g/h;
}

private double square (int i)
{
return Math.pow(2, i);
}

private double log10 (double j)
{
return Math.log10(j);
}
}

Now, let’s try to execute our methods with the Arithmetic class  (using the same numerical parameters from the previous example):

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

And here’s what happens when we try to run the code:

Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – add(int,int) has private access in ProgramDemo
at Arithmetic.main(Arithmetic.java:6)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

Since all of the ProgramDemo methods are private, we can’t access them from the Arithmetic class  (not even with the extends keyword). Notice that the error is something called an exception, which I will discuss more in a future post.

  • I imagine there’s probably a way to access private methods from another class, but I haven’t figured it out yet. Once I do, I’ll discuss it in a future post.

Now let’s make all of the ProgramDemo methods protected:

public class ProgramDemo
{
protected int add (int a, int b)
{
return a+b;
}

protected int subtract (int c, int d)
{
return d-c;
}

protected int multiply (int e, int f)
{
return e*f;
}

protected double divide (double g, double h)
{
return g/h;
}

protected double square (int i)
{
return Math.pow(2, i);
}

protected double log10 (double j)
{
return Math.log10(j);
}
}

And let’s run the code in the Arithmetic class (without changing the parameters):

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

Here’s the output:

run:
BUILD SUCCESSFUL (total time: 4 seconds)

OK, so this is a weird case where the methods are still accessible but don’t return anything; this is made even weirder since the methods aren’t of type void , so you would think that we would see returned values.

Interestingly enough, I tried several ways to fix my code so that the output would show (and yet none of them worked). Some of my attempted solutions include:

  • Creating a new package-JavaLesson11-and moving the Arithmetic and ProgramDemo classes to that package (I originally had them in the default package)
    • It’s very easy to create a new package in NetBeans. Simply click on the New File button (located above the interface) and when you are asked what type of file you want, simply click on New Package.
  • Using the phrase extends ProgramDemo in the Arithmetic class-I did this both before and after moving each of these classes into the JavaLesson11 package
    • This also did not work. I thought this would certainly would work, since protected methods can be accessed by subclasses of a certain class (the word extends make a class a subclass of whatever that class extends).
    • Also, after I moved Arithmetic and ProgramDemo to the JavaLesson11 package, I thought using extends would certainly work, since protected methods can be accessed by any class in the same package.

Cases like these are why I try to avoid using protected methods in my Java code. I’ll likely stick to public and private methods from here on out.

Now, the last thing I want to demonstrate is how void methods work. Im going to change two methods in ProgramDemo to void and see if that impacts the output:

package JavaLesson11;

public class ProgramDemo
{
public void add (int a, int b)
{
System.out.println(a+b);
}

protected void subtract (int c, int d)
{
System.out.println(d-c);
}

protected int multiply (int e, int f)
{
return e*f;
}

protected double divide (double g, double h)
{
return g/h;
}

protected double square (int i)
{
return Math.pow(2, i);
}

protected double log10 (double j)
{
return Math.log10(j);
}

}

And here’s the ArithmeticClass along with the corresponding output:

package JavaLesson11;

public class Arithmetic extends ProgramDemo
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

run:
64
4
BUILD SUCCESSFUL (total time: 0 seconds)

So I ran the code and only get two numbers-64 and 4-which correspond to the add and subtract methods, respectively. Surprisingly, none of the other results from my other methods were printed.

How could that be? First of all, I only made the add and subtract methods void. As a result, I changed the body of each method by replacing the return statement with a System.out.println line that does the same thing as the non-void add and subtract methods. My guess is that since add and subtract are the only two methods with a System.out.println statement in the body of the method, the results of these methods were the only ones that were displayed in the output.

Thanks for reading. It’s good to be back,

Michael

 

 

Java Lesson 10: Encapsulation

Hello everybody,

It’s Michael, and I’m back with another series of Java lessons (but there will be plenty more Pythons lessons to come). Today’s Java lesson will be on encapsulation.

Encapsulation is a process in Java that wraps (or encapsulates) code and data together in a single unit. The whole point of encapsulation is to ensure that sensitive program data (whatever that might entail) is hidden from users.

There are two things you need to do to in order to encapsulate your data, which include:

  • declaring class variables as private, which means that they can only be accessed in the same class
  • provide getter and setter methods to access and modify the value of a private variable.

Getter methods return the value of a private variable while setter methods set the value of a private variable. Here’s an example of a program with getter and setter methods:

public class ProgramDemo
{
private String model;
private int year;

public String getModel ()
{
return model;
}

public void setModel (String newModel)
{
this.model = newModel;
}

public int getYear ()
{
return year;
}

public void setYear (int newYear)
{
this.year = newYear;
}
}

In this program, there are two private variables relating to cars-model (referring to what model the car is) and year (referring to the car’s release year). Both variables have getter and setter methods. For each of the getter methods, the syntax would be like this:

  • public [variable type] get[variable name with first letter capitalized] ()

The body of the getter method would consist of a return statement followed by the variable’s name (such as return model). The setter methods are structured differently; here’s the syntax:

  • public void set[variable name with first letter capitalized] (variable type followed by variable name)

Regardless of variable type, all setter methods are of type void, meaning that they have no return statement. Also, when I mentioned that the parameters for setter methods are the variable type followed by the variable name, the variable name would have its first letter capitalized and it would have the word new in front of the name (like I did with newYear and newModel).

The body of setter methods consists of a single line of code (just as with getter methods). That single line of code would appear as this.[variable name] = new[variable name with first letter capitalized]. The word this refers to the current object and will always appear in the body of setter methods.

Now let’s see our setter and getter methods at work, using a separate class called Car:

public class Car
{
public static void main (String [] args)
{
ProgramDemo myCar = new ProgramDemo ();
myCar.setModel(“Honda Civic”);
myCar.setYear(2007);
System.out.println(myCar.getModel());
System.out.println(myCar.getYear());
}
}

Using both of my setter methods, I set the model to Honda Civic and the year to 2007. I then use both of my getter methods-along with System.out.println-to display the model name and year of the car as the output (which is shown below)

Honda Civic
2007

  • The best part about this program is that I didn’t need to use the extends statement to access the getter and setter methods in ProgramDemo. Rather, I simply created the variable myCar as an object of the ProgramDemo class and I was able to access the getter and setter methods for both variables.

Thanks for reading,

Michael

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

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 9: Inheritance, Polymorphism & Subclasses

Hello everybody,

It’s Michael, and today’s Java lesson will be on inheritance, polymorphism & subclasses.

First of all, what is inheritance? In Java, it’s possible for one class to inherit the attributes and methods of another class. Using the keyword extends, any class can inherit methods and attributes from another class. The class that is inheriting the methods and attributes is called the subclass or child class while the class that is providing the methods for the subclass is called the parent class or superclass.

Polymorphism is related to inheritance, but the two aren’t interchangeable. Inheritance lets us use methods and attributes from another class by means of the extends keyword while polymorphism lets us use those inherited methods to perform a single action in different ways.

Let’s say we have a superclass called Sport which has a single method-score. Subclasses of Sport could include Bowling, AmericanFootball, Golf, Basketball, etc. and each subclass would have their own implementation of a scoring system* (for instance, baseball would use runs, golf would use par, etc.)

  • *this is where polymorphism would come in

Here’s some code we can use to approach the problem in the above example (keep in mind I didn’t run any of this on NetBeans; I’m just using this solely as an example):

Let’s start with some code for the main class:

public class Sport

{

public void score ()

{

System.out.print(“Score system: “);

}

}

 

 

And here’s the code for two subclasses-AmericanFootball and Baseball:

class AmericanFootball extends Sport

{

public void score ()

{

System.out.print(“Score system: Points”)

}

}

 

class Baseball extends Sport

{

public void score ()

{

System.out.print (“Score system: Runs”);

}

}

As you can see, there is no main method for the main class Sport but rather the void method score, which is used in my two subclasses-AmericanFootball and Baseball. One thing you will notice is that-and this is where polymorphism comes into play-the score method produces a different output for each class. For instance, if you were to create an object of the main class-Sport-and call the score method, you would get the output Score system: . If you were to create an object of class AmericanFootball and call the score method, you would get the output Score system: Points. If you did the same thing for the Baseball class, you would get the output Score System: Runs.

My point is that with polymorphism, you can use the same method across various classes and tailor the method to each class.

Thanks for reading,

Michael

Java Lesson 8: Arrays

Hello everybody,

It’s Michael, and today’s Java post will be about arrays. But what exactly do arrays do in Java?

Arrays are basically a list of variables that are referred to by a common name. Here’s an example:

Florida Ohio Georgia Mississippi Texas Montana

This is an array of states, which I will call states.

You can make arrays for variables of any Java type, including:

  • int
    • And any numerical type for that matter (i.e. double, float)
  • char
  • boolean
  • String

However, you cannot have several variable types in an array (so no mixing String elements with int elements). For instance, if you wanted to include 737 Down Over ABQ in your array, the 737 would have to be a String in order to make the array work (assuming Down Over ABQ are all String).

Now let me demonstrate a simple array program:

package javalessons;

public class JavaLessons
{

public static void main(String[] args)
{
String [] stateCaps = {“Helena”, “Salem”, “Tallahassee”, “Atlanta”, “St.Paul”, “Pierre”, “Columbus”, “Providence”};
System.out.println(stateCaps[4]);
}
}

And here are two sample outputs (using a different index for each array):

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

run:
St.Paul
BUILD SUCCESSFUL (total time: 0 seconds)

The first thing I did in the program is to create my array declaration-String [] stateCaps = {"Helena", "Salem", "Tallahassee", "Atlanta", "St.Paul", "Pierre", "Columbus", "Providence"}. The point of the array declaration is to create an array and POSSIBLY fill it with elements.

I say POSSIBLY because there are three ways I can go about create my array and filling it with elements. Here are some possibilities:

  • Do what I did in the aforementioned program, which is to create the array and the elements in the same line of code (separated by an equals sign)
  • Create the array and allocate space to the array in the same line, which would mean I would have written String [] stateCaps = new String [8] to create a String array with 8 values. Meanwhile, I would have added elements in 8 separate lines of code, starting with stateCaps[0]="Helena" and continuing on until I fill the array.
  • Create a for loop. More on that later in this post.

OK, here’s something I want to mention about that second bullet point. Each element in an array is called an index (plural: indices). However, the first index in an array is [0] not [1] since array indices are counted starting from 0, not 1. So the first index in an array is [0], the second index is [1], the third index is [2], and so on.

In each of my outputs, I chose a different index, and thus got a different output each time. The first output-Tallahassee-corresponds to index 2-or the third element in the array, which is “Tallahassee”. The second output-St.Paul-corresponds to index 4-or the fifth element in the array, which is “St.Paul”.

Next, remember how I mentioned that you could use a random number generator in arrays in my previous post? Here’s how you can do that (using a different array):

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
String [] cartoons = {“Family Guy”, “Spongebob”, “Simpsons”, “South Park”,
“Archer”, “Daniel Tiger’s Neighborhood”, “Arthur”, “Looney Tunes”,
“Big Mouth”, “Rick & Morty”};
Random gen = new Random ();
int index = gen.nextInt(9);

System.out.println(cartoons[index]);
}
}

And here are two sample outputs:

run:
Big Mouth
BUILD SUCCESSFUL (total time: 0 seconds)

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

In this program, I first imported java.util.Random, which is what you need to do if you plan on using a random number generator in your program. I also remembered to create Random and int variables, which you need to do in order to have a random number generator handy and, in the case of the int variable, set the upper limit for the random number generator. In this case, the upper limit for my generator is 9, since there are 10 elements in my array (remember array elements start counting from 0). Had I used 10 as the upper limit, there is a chance I would have gotten an error message since there is no index 10. I then created an array-cartoons-and filled it with 10 elements (10 American cartoons).

For my output, I asked the program to print out a random element each time I run the program. In my first sample output, index 8 was displayed (corresponding to Big Mouth) while in my second output, index 1 was displayed (corresponding to Spongebob).

Now let me show you how to fill in an array using a for loop:

package javalessons;

public class JavaLessons
{

public static void main(String[] args)
{
int [] multiples = new int [15];

for (int i = 0; i <= 14; i++)
{
multiples[i]=i*8;
}

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

And here are two sample outputs (each using a different index):

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

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

This program demonstrates a very simple way to fill in an array using a for loop. I used my for loop to fill in my array with multiples of 8, hence the I*8. I first created my array in the line directly above the for loop, then I created the for loop to fill my array with elements. In my for loop, I started my counter at 0 (remember that array indices start from 0), asked it to stop at 14 (since I will have 15 elements in my array), and asked it to increment by 1 after each iteration.

  • I’ll admit that the new int [15] may seem redundant since I already determined that my loop will have 15 iterations (and thus 15 elements).

My sample outputs printed indexes 3 and 6 (the 4th and 7th elements respectively), which correspond to the numbers 24 and 48. Remember that since I started this loop with 0, the first element will be 0, since 0 times 8 is 0.

Last but not least, I will introduce the concept of two dimensional arrays using a combination of a for loop and a random number generator. Here’s a sample program:

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
int [] [] twoDim = new int [6][6];
Random gen = new Random ();
int boundary = gen.nextInt(35);

for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 5; j++)
{
twoDim [i][j] = boundary;
}
}

System.out.println (twoDim[2][3]);
}
}

And here are two sample outputs:

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

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

The process of working with two-dimensional arrays (or other multidimensional arrays for that matter) is a little different than the process of working with one dimensional arrays. First of all, you would need a nested for loop (or a for loop within a for loop) to traverse through (and possibly fill in) your array. Second, you would need two squares [] [] to initialize the array as opposed to just one [].

  • You don’t always need a nested for loop to fill in a two dimensional array. Plus if you are dealing with non-numerical elements like String, a loop isn’t very practical to use.
  • Here’s another way to fill in a 2-dimensional array, using String elements:
    • Let’s say our array is 3 by 3.
    • This is another way to fill in elements:
      • String [][] cities = {{"Fort Collins", "Mentor", "Miami"}, {"Bozeman", "Annapolis", "Pittsburgh"}, {"Boston", "Omaha", "Manhattan"}}
      • Since this array is 3 by 3, we would have 3 groups of 3 elements each.
  • Here’s a handy rule when it comes to two dimensional arrays:
    • For an array with dimensions of [x][y], create x groups of y elements each.

The “indexes start at 0” rule applies here. Here’s the index structure for the 6 by 6 array I created above:

Screen Shot 2019-04-25 at 4.21.52 PM

The first index would be [0][0] while the final index would be [5][5]. If you wanted to select the element on the second row and fourth column, that would correspond to [1][3].  Remember that the row always comes first, followed by the column.

In my sample outputs,  I selected indexes [2][3] and [3][0], which printed out 24 and 1, respectively. Keep in mind that even if you use the same indexes, you might get a different output each time due to the use of the random number generator in this program. However, I set the upper limit to 35, which means the number printed will always be between 0 and 35.

One last thing I want to address is that you can create arrays that are more than two dimensions. For instance, if you wanted to make a 4-dimensional array, you would include 4 squares-[][][][]. As to how many elements an array like this can hold, just find the product of all of the numbers in the dimension brackets (which would be to the right of the equals sign). For instance, if you have a 4-dimensional array like this-String [][][][] names = new String [3][9][2][4]-multiply the numbers in the dimension brackets to see how many elements this array will hold (3*9*2*4=216; this array will hold 216 elements).

Thanks for reading,

Michael

 

Java Lesson 7: Random Number Generator

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

Java Program Demo 1: Factorials and Fibonacci Sequences

Hello everybody,

It’s Michael, and today’s Java post will be a little different from the previous six because I am not giving you guys a lesson today. See, when I launched this blog in June 2018, I said I was going to posts lessons and analyses with various programs. However, in the case of Java, I feel it is better to give you guys program demos that cover the concepts I’ve discussed so far (loops, if-else statements, etc.). In this post, I will show you guys two programs that cover all the Java concepts I’ve discussed so far.

Here is this code for the first program (video in link)-Fibonacci sequence program:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

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

int start = 0;
int t2 = 1;

if (num >= 0)
{
while (start <= num)
{
System.out.print(start + ” + “);

int sum = start + t2;
start = t2;
t2 = sum;
}
}

else
{
System.out.println(“Need a 0 or a positive number”);
}
}
}

This program prints every number in the Fibonacci sequence up to a certain point. If you’re wondering, the Fibonacci sequence is a pattern of numbers that starts with 0 and 1 and calculates each subsequent element by finding the sum of the two previous numbers.

  • Here are the first 10 numbers of the Fibonacci sequence-0,1,1,2,3,5,8,13,21,34,55. Notice how every element after the 3rd is the sum of the previous two numbers (e.g. 13 is found by calculating 5+8-the two numbers that directly precede 13 in the series)

To calculate the Fibonacci sequence, I first ask the user to type in a number. That number will serve as the endpoint for my while loop where I calculate each element in the Fibonacci sequence; in other words, my while loop will find every element in the sequence until it reaches the closest possible number to the user’s input. For instance, if I wanted to find every number in the Fibonacci sequence stopping at 600, the program would stop at the closest possible number to 600-which is 377.

  • I decided to add an endpoint because the Fibonacci sequence is infinite, and had I decided not to have an endpoint, I would’ve created an infinite loop.

Notice the if-else statement in my program. The loop will only run IF the user inputs a positive number. Otherwise, the user will just see a message that goes Need a 0 or a positive number. I decided to include the if-else statement since Fibonacci sequences don’t have any negative numbers.

Let’s see some sample output:

run:
Please choose a number:
112
0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 + BUILD SUCCESSFUL (total time: 6 seconds)

run:
Please choose a number:
-5
Need a 0 or a positive number
BUILD SUCCESSFUL (total time: 3 seconds)

As you can see, my first output-112-displays the Fibonacci sequence up to 112 while my second output-negative 5-displays a message that is shown when a negative number is chosen.

Here is the code for my next program (video in link)-Factorial program:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

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

long factorial = 1;

if (num >= 1)
{
for(int i = 1; i <= num; ++i)
{
factorial *= i;
}
System.out.println(“The factorial of ” + num + ” is ” + factorial);
}

else
{
System.out.println (“Number is too low”);
}
}
}

This program calculates the factorial of a number greater than 0. For those wondering, a factorial is the product of a positive number and all positive numbers below it (stopping at 1). For instance 3 factorial is 6, since 3*2*1=6. Just so you guys know, factorials are denoted by the exclamation point (!), so 3 factorial is 3!.

I have three conditional statements in this program that account for the three possible scenarios of user input (>0,0, and <0). If the user enters a number greater than 0, then the for loop will execute and the factorial of the number will be calculated. If the user enters 0, then the message The factorial of 0 is 1 will be displayed, since 0!=1. If the user enters a negative number, then the message Number is too low will be displayed, since factorials only involve positive numbers.

  • If you are wondering why I used long for the factorial variable, I thought it would be more appropriate since factorials can get pretty long (13! is over 6 billion), and long has a wider range than int (9 quintillion as opposed to 2 billion).

Now, let’s see some sample output

run:
Please choose a number:
11
The factorial of 11 is 39916800
BUILD SUCCESSFUL (total time: 12 seconds)

run:
Please choose a number:
0
The factorial of 0 is 1
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please choose a number:
-14
Number is too low
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please choose a number:
344
The factorial of 344 is 0
BUILD SUCCESSFUL (total time: 3 seconds)

In the first output sample, I chose 11 and got 39,916,800 as the factorial (11!=39,916,800). In the second output sample, I chose 0 and got 1 as the factorial (remember than 0! is 1). In the third output sample, I chose -14 and got the Number is too low message since factorials only involve positive integers.

Now I know I mentioned that there were three possible scenarios for this program. There are actually 4. See, if you type in a number like 700 or 344 (as I did above), you will get 0 as the factorial, even though the actual factorial will be considerably larger. A 0 will be displayed if the actual factorial is greater than 9 quintillion since long doesn’t extend past 9 quintillion.

This concludes my current series of Java posts, but don’t worry, there will be more Java lessons soon! In the meantime, you can look forward to more R posts.

Thanks for reading,

Michael

Java Lesson 6: Loops

Hello everybody,

It’s Michael, and today’s lesson will be on Java loops. For those who do not know, loops repeat groups of statements in Java by executing the same actions over and over until a certain condition is met. The block of code inside the loop is called the body, while each repeat of the loop is referred to as an iteration of the loop.

Loops are important because Java programs often need to repeat actions. For instance, if you were trying to make a step-counter program, you would need a loop to increase the step-count by 1 every time a step is taken. You would ideally want to keep increasing by 1 until a certain count is reached-let’s say 10,000 steps (though you could also make your step-counter loop infinite).

There are three types of loops-while, do-while, and for-which each have their own distinct functions.

First off, I’ll discuss the for loop. Here’s a program demonstrating the use of a for loop (source code below)-For loops demo.

package javalessons;

public class JavaLessons
{

public static void main(String[] args)
{

for (int i = 2; i <= 400; i*=2)
{
System.out.println(i);
}
}
}

The basic structure of the for loop goes like this:

  • for (variable assignment; condition to end the for loop; updating action), followed by the body
  • ALWAYS remember to write your loop in this order; the compiler will throw error messages if you try to do otherwise!

In this program, I am using a for loop to calculate successive powers of 2 and display the results from top to bottom. My variable assignment-int i=2-goes first so that the loop knows the starting condition (that I am starting off with 2). The condition to end the loop-i <= 400-goes next so that the loop knows where to end (the program will keep displaying powers of 2 until a number that is either the closest to 400 or exactly 400 is reached). The updating condition-i*=2-tells the loop how to update the output (keep multiplying i by 2 until the ending condition is met).

  • By the way, you can put i = i* 2 instead of i*=2 . Either will be accepted by the compiler, the latter is just convenient shorthand. The same logic goes for addition, division, and subtraction.

Now let’s try some sample output:

run:
2
4
8
16
32
64
128
256
BUILD SUCCESSFUL (total time: 0 seconds)

The program will display all the powers of 2 that are less than 400, starting with 2 and ending with the maximum power of 2 that is less than 400-296.

Next I’ll discuss the while loop, with a demo program (source code below)-

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Pick an even numbered year: “);
int year = sc.nextInt();

int baseYear = 2100;
while (year < baseYear)
{
if (year % 4 != 0)
{
System.out.println (year);
System.out.println(“Winter Olympics Year”);
}

else
{
System.out.println (year);
System.out.println(“Summer Olympics Year”);
}

year += 4;
}
}
}

The basic structure of the while loop goes like this:

  • while (condition to keep while loop going), followed by the body.
  • Variable declarations are always included outside of the while loop; ideally just above the line where the while loop begins.

In this program, I enter an even numbered year and the program will tell me if it’s a Winter or Summer Olympics year and based on that, it will tell me the next Winter/Summer Olympics years until 2100 (since my while condition was that the loop will keep going and increasing the year by 4 until 2100 is reached).

  • If you’re wondering what the % means in Java, it means remainder. The statement if (year % 4 != 0) executes the output in the body of the code if the year entered has a remainder and isn’t divisible by 4, since Winter Olympics years occur during even numbered years that aren’t easily divisible by 4 (2006, 2010, 2014, and so on). If the year entered is divisible by 4, then Summer Olympics years would be displayed, since they occur during even-numbered leap years (which are years divisible by 4)-think 2012, 2016, 2020 and so on.

Let’s try some sample output:

Output 1:

run:
Pick an even numbered year:
2014
2014
Winter Olympics Year
2018
Winter Olympics Year
2022
Winter Olympics Year
2026
Winter Olympics Year
2030
Winter Olympics Year
2034
Winter Olympics Year
2038
Winter Olympics Year
2042
Winter Olympics Year
2046
Winter Olympics Year
2050
Winter Olympics Year
2054
Winter Olympics Year
2058
Winter Olympics Year
2062
Winter Olympics Year
2066
Winter Olympics Year
2070
Winter Olympics Year
2074
Winter Olympics Year
2078
Winter Olympics Year
2082
Winter Olympics Year
2086
Winter Olympics Year
2090
Winter Olympics Year
2094
Winter Olympics Year
2098
Winter Olympics Year
BUILD SUCCESSFUL (total time: 10 minutes 55 seconds)

I chose an even-numbered non-leap year, 2014, and the program printed out all Winter Olympics years from 2014 until the Games happening right before the year 2100 (the 2098 Winter Games).

Output 2:

run:
Pick an even numbered year:
2020
2020
Summer Olympics Year
2024
Summer Olympics Year
2028
Summer Olympics Year
2032
Summer Olympics Year
2036
Summer Olympics Year
2040
Summer Olympics Year
2044
Summer Olympics Year
2048
Summer Olympics Year
2052
Summer Olympics Year
2056
Summer Olympics Year
2060
Summer Olympics Year
2064
Summer Olympics Year
2068
Summer Olympics Year
2072
Summer Olympics Year
2076
Summer Olympics Year
2080
Summer Olympics Year
2084
Summer Olympics Year
2088
Summer Olympics Year
2092
Summer Olympics Year
2096
Summer Olympics Year
BUILD SUCCESSFUL (total time: 3 seconds)

I chose an even-numbered leap-year, 2020, and the program printed out all Summer Olympics years from the year 2020 until the Games right before the year 2100 (which would be the 2096 Summer Games).

Output 3:

run:
Pick an even numbered year:
2110
BUILD SUCCESSFUL (total time: 3 seconds)

I chose a year greater than 2100-2110 and the loop doesn’t execute at all, since my initial response exceeded the base year.

The main difference between the while and for loops is that variable declarations and updating conditions (like incrementing variables) are done either in the body of the loop or outside the loop when dealing with while, but both of those things are handled in the constructor of the loop when dealing with for.

Finally, the last loop I will discuss is the do-while loop, which is very similar to the while loop, except that the body of a do-while loop always runs at least once, while the body of a while loop might not run at all. This is because the body of the do-while loop comes before the constructor, not after.

Here’s the basic structure of the do-while loop:

  • do {body of loop} while (condition to keep loop running)
  • After each iteration, the condition is checked to see if it still holds true. As long as it does, the loop keeps running.

Here’s a sample program (code below)-Do-while loop demo:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

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

double base = 1000;
do
{
number *= 1.05;
System.out.print (number + ” , “);
} while (number <= base);

}
}

In this program, I enter a number and the do-while loop will calculate 5% growth so long as the number being increased by 5% is less than the base of 1000. I could’ve written the program using a while loop, but there would’ve been a chance that the while loop might not have run at all, but the do-while loop will run at least once, which I wanted (plus I felt it was important to discuss).

Let’s try some sample output:

Pick a number:
456
478.8 , 502.74 , 527.8770000000001 , 554.2708500000001 , 581.9843925000001 , 611.0836121250002 , …..

I typed in 456, and the program kept displaying 5% increases starting with the first increase-478.8-until the program reached a number that was either 1000 or the closest possible calculation to 1000.

Now, when dealing with Java loops, one thing you should watch out when writing your code is the infinite loop, which are loops that don’t end.

Infinite loops can be caused by something as simple as a sign. Here’s an infinite loop from the do-while example in this post (code first, then output)-:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

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

double base = 1000;
do
{
number *= 1.05;
System.out.print (number + ” , “);
} while (number >= base);
}
}

run:
Pick a number:
45600
47880.0 , 50274.0 , 52787.700000000004 , 55427.08500000001 , 58198.43925000001 , 61108.361212500015 , 64163.779273125016 , 67371.96823678126 , 70740.56664862033 , 74277.59498105134 , 77991.47473010392 , 81891.04846660912 , 85985.60088993958 , 90284.88093443656 , 94799.12498115838 , 99539.08123021631 , 104516.03529172714 , 109741.8370563135 , 115228.92890912917 , 120990.37535458563 , 127039.89412231492 , 133391.88882843067 , 140061.4832698522 , 147064.55743334483 , 154417.78530501208 , 162138.6745702627 , 170245.60829877583 , 178757.88871371464 , 187695.78314940038 , 197080.5723068704 , 206934.60092221393 , 217281.33096832462 , 228145.39751674086 , 239552.66739257792 , 251530.3007622068 , 264106.81580031716 , 277312.15659033303 , 291177.7644198497 , 305736.6526408422 , 321023.4852728843 , 337074.6595365285 , 353928.39251335495 , 371624.8121390227 , 390206.05274597387 , 409716.3553832726 , 430202.1731524362 , 451712.28181005805 , 474297.89590056095 , 498012.79069558904 , 522913.4302303685 , 549059.1017418869 , 576512.0568289813 , 605337.6596704304 , 635604.5426539519 , 667384.7697866495 , 700754.008275982 , 735791.7086897811 , 772581.2941242702 , 811210.3588304837 , 851770.876772008 , 894359.4206106084 , 939077.3916411388 , 986031.2612231958 , 1035332.8242843556 , 1087099.4654985734 , 1141454.4387735021 , 1198527.1607121774 , 1258453.5187477863 , 1321376.1946851755 , 1387445.0044194343 , 1456817.2546404062 , 1529658.1173724267 , 1606141.023241048 , 1686448.0744031004 , 1770770.4781232555 , 1859309.0020294185 , 1952274.4521308895 , 2049888.1747374341 , 2152382.583474306 , 2260001.7126480215 , 2373001.7982804226 , 2491651.8881944437 , 2616234.482604166 , 2747046.2067343746 , 2884398.5170710934 , 3028618.442924648 , 3180049.3650708804 , 3339051.8333244245 , 3506004.4249906456 , 3681304.646240178 , 3865369.8785521872 , 4058638.372479797 , 4261570.291103787 , 4474648.805658977 , 4698381.245941926 , 4933300.308239022 , 5179965.323650974 , 5438963.589833523 , 5710911.7693252 , 5996457.35779146 , 6296280.225681033 , 6611094.236965085 , 6941648.94881334 , 7288731.396254007 , 7653167.966066708 , 8035826.364370043 , 8437617.682588546 , 8859498.566717973 , 9302473.495053872 , 9767597.169806566 , 1.0255977028296895E7 , 1.076877587971174E7 , 1.1307214673697326E7 , 1.1872575407382194E7 , 1.2466204177751305E7 , 1.308951438663887E7 , 1.3743990105970815E7 , 1.4431189611269357E7 , 1.5152749091832826E7 , 1.5910386546424467E7 , 1.6705905873745691E7 , 1.7541201167432975E7 , 1.8418261225804623E7 , 1.9339174287094854E7 , 2.0306133001449596E7 , 2.1321439651522078E7 , 2.2387511634098183E7 , 2.3506887215803094E7 , 2.468223157659325E7 , 2.5916343155422915E7 , 2.7212160313194063E7 , 2.8572768328853767E7 , 3.0001406745296456E7 , 3.150147708256128E7 , 3.3076550936689347E7 , 3.4730378483523816E7 , 3.646689740770001E7 , 3.829024227808501E7 , 4.020475439198926E7 , 4.2214992111588724E7 , 4.432574171716816E7 , 4.654202880302657E7 , 4.8869130243177906E7 , 5.1312586755336806E7 , 5.387821609310365E7 , 5.6572126897758834E7 , 5.9400733242646776E7 , 6.237076990477912E7 , 6.548930840001808E7 , 6.876377382001899E7 , 7.220196251101995E7 , 7.581206063657095E7 , 7.96026636683995E7 , 8.358279685181947E7 , 8.776193669441044E7 , 9.215003352913097E7 , 9.675753520558752E7 , 1.0159541196586691E8 , 1.0667518256416026E8 , 1.1200894169236827E8 , 1.1760938877698669E8 , 1.2348985821583603E8 , 1.2966435112662785E8 , 1.3614756868295926E8 , 1.4295494711710724E8 , 1.5010269447296262E8 , 1.5760782919661075E8 , 1.654882206564413E8 , 1.7376263168926337E8 , 1.8245076327372655E8 , 1.915733014374129E8 , 2.0115196650928354E8 , 2.1120956483474773E8 , 2.2177004307648513E8 , 2.328585452303094E8 , 2.4450147249182487E8 , 2.5672654611641613E8 , 2.695628734222369E8 , 2.830410170933488E8 , 2.971930679480162E8 , 3.12052721345417E8 , 3.276553574126879E8 , 3.4403812528332233E8 , 3.6124003154748845E8 , 3.793020331248629E8 , 3.9826713478110605E8 , 4.181804915201614E8 , 4.390895160961695E8 , 4.6104399190097797E8 , 4.840961914960269E8 , 5.0830100107082826E8 , 5.337160511243697E8 , 5.604018536805882E8 , …

As you can see, I changed the sign in the do-while loop from “less than or equal to” to “greater than or equal to”. If you type a number greater than the base of 1000, then your loop can go on and on, as you can see here (of course, you can always hit the stop button).

Before I go, here are the answers to the number conversion problems from my previous post Java Lesson 5: Java Numbering Systems:

Binary-to-Decimal

  • 0110-6
  • 10011-19
  • 1100001-97
  • 1001001-73

Octal-to-Decimal

  • 523-339
  • 3455-1837
  • 123023-42515
  • 2346523-642387

Hexadecimal-to-Decimal

  • 4BF-1215
  • 67AC-26540
  • AF12-44818
  • 192DCC-1650124

Thanks for reading.

Michael