Java Program Demo 3: More Fun With Method Making, Exceptions, Recursion, and Encapsulation

Advertisements

Hello readers,

It’s Michael, and today’s post will be another Java program demo utilizing the concepts covered in the previous four posts (encapsulation, method making, exceptions, and recursion). I thought this would be a good post to show more examples using these four concepts (as well as build upon the other concepts I discussed in the previous 9 Java posts, because after all, the harder concepts in Java build upon the easier concepts).

First let’s do an encapsulation demo. Here’s our method class (the one that has our getter and setter methods):

package demo3;

public class Demo3
{
private double surfaceArea;
private double volume;

public double setSurfaceArea (double radius, double height)
{
surfaceArea = (2*3.14*Math.pow(radius,2)) + (2*3.14*radius*height);
return surfaceArea;
}

public double setVolume (double radius, double height)
{
volume = (3.14*Math.pow(radius, 2)*height);
return volume;
}

}

And here’s our main class (the class where we will run the program):

package demo3;
import java.util.Scanner;

public class DemoClass3
{
public static void main (String [] args)
{
Demo3 cylinder = new Demo3();

Scanner sc = new Scanner(System.in);

System.out.println(“Please give me a radius: “);
double r = sc.nextDouble();

System.out.println(“Please give me a height: “);
double h = sc.nextDouble();

System.out.println(“The cylinder’s surface area is ” + cylinder.setSurfaceArea(r, h));
System.out.println(“The cylinder’s volume is ” + cylinder.setVolume(r, h));
}
}

And here’s some sample output:

run:
Please give me a radius:
9.5
Please give me a height:
11.2
The cylinder’s surface area is 1234.962
The cylinder’s volume is 3173.912
BUILD SUCCESSFUL (total time: 30 seconds)

In the Demo3 class, I have two private double variables-surfaceArea and volume. My two setter methods-setSurfaceArea and setVolume-will set the values of the surfaceArea and volume variables. Oh, and in case you’re wondering where I got the formulas from, they are the formulas for the surface area and volume of a cylinder, respectively.

You will notice that I don’t have any getter methods here. Why? Since I am using formulas to set the values of surfaceArea and volume, using only the setter methods is fine; due to the nature of this program, there is no need to use getter and setter methods (and the code might have been more confusing if I had used both getters and setters).

In my main class, I have a Scanner object and two doubles-r and h-that will serve as the parameters for each setter method (r will be radius and h will be height). R and h will be set based on the user’s input.

  • One thing I wanted to mention that I didn’t mention earlier is that you don’t have to use the words get and set in your getter and setter methods, but it’s a good idea to do so.

Next, here’s a program demonstrating method making and exception handling. First, here’s the method class (the class that contains the method(s) needed for the program):

package demo3;

public class Demo3
{
private double windchill;

public void findWindchill (double airTemp, double windSpeed)
{
try
{
windchill = 35.74 + (0.6215*airTemp) – (35.75*Math.pow(windSpeed, 2)) + (0.4275*airTemp*Math.pow(windSpeed, 16));
System.out.println(“The windchill is: ” + windchill);
}

catch (Exception e)
{
System.out.println(“Sorry please enter a number”);
}
}
}

And here is the main class (the class from where we will run the program):

package demo3;

public class Demo3
{
private double windchill;

public void findWindchill (double airTemp, double windSpeed)
{
try
{
windchill = 35.74 + (0.6215*airTemp) – (35.75*Math.pow(windSpeed, 2)) + (0.4275*airTemp*Math.pow(windSpeed, 16));
System.out.println(“The windchill is: ” + windchill);
}

catch (Exception e)
{
System.out.println(“Sorry please enter a number”);
}
}
}

And here are two sample outputs (one where the exception runs and one where the program runs normally):

run:
Please enter the temperature:
12
Please enter wind speed:
55
The windchill is : 3.596834017946246E28
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please enter the temperature:
12
Please enter wind speed:
H
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at demo3.DemoClass3.main(DemoClass3.java:15)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

In this program, the method findWindchill will calculate the temperature with windchill using airTemp and windSpeed as parameters-both of which are double.

In the method findWindchill , I have included a try-catch statement. In the try portion, the block of code I will test will calculate and display the windchill. In the catch portion, the message Sorry please enter a number will be displayed should the method catch an error (which would involve either airTemp or windSpeed not being double).

Or so you would think that the Sorry please enter a number message will be displayed (I thought this would happen too). Here’s what you really see:

Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at demo3.DemoClass3.main(DemoClass3.java:15)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

So why don’t you see the Sorry please enter a number message? It’s because that, when dealing with double input, Java will automatically throw an InputMismatchException if the input is non-numeric.

In other words, writing a try-catch statement in my findWindchill method wasn’t necessary. I’ll admit that I didn’t realize this at first, and only found out this would happen after browsing through a few StackOverflow forums. Hey, even I learn new things in programming every now and then.

  • StackOverflow is a great resource for any coding questions you might have, but keep in mind that you might have to look through a few forums until you get the answer that you need.

Lastly, here’s a recursion demo, starting with the method class. Notice anything familiar about this program?:

public class Demo3
{
private int month;
private int day;
private String year;

public String findMonth (int month)
{
String m = null;

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

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

}

}

return m;
}

public String findDay1 (int day)
{
String d = null;

{
switch(day)
{
case 1: d = “1st”; break;
case 2: d = “2nd”; break;
case 3: d = “3rd”; break;
case 4: d = “4th”; break;
case 5: d = “5th”; break;
case 6: d = “6th”; break;
case 7: d = “7th”; break;
case 8: d = “8th”; break;
case 9: d = “9th”; break;
case 10: d = “10th”; break;
case 11: d = “11th”; break;
case 12: d = “12th”; break;
case 13: d = “13th”; break;
case 14: d = “14th”; break;
case 15: d = “15th”; break;
case 16: d = “16th”; break;
case 17: d = “17th”; break;
case 18: d = “18th”; break;
case 19: d = “19th”; break;
case 20: d = “20th”; break;
case 21: d = “21st”; break;
case 22: d = “22nd”; break;
case 23: d = “23rd”; break;
case 24: d = “24th”; break;
case 25: d = “25th”; break;
case 26: d = “26th”; break;
case 27: d = “27th”; break;
case 28: d = “28th”; break;
case 29: d = “29th”; break;
case 30: d = “30th”; break;

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

return d;
}
}

public String findDay2 (int day)
{
String d2 = null;

switch(day)
{
case 1: d2 = “1st”; break;
case 2: d2 = “2nd”; break;
case 3: d2 = “3rd”; break;
case 4: d2 = “4th”; break;
case 5: d2 = “5th”; break;
case 6: d2 = “6th”; break;
case 7: d2 = “7th”; break;
case 8: d2 = “8th”; break;
case 9: d2 = “9th”; break;
case 10: d2 = “10th”; break;
case 11: d2 = “11th”; break;
case 12: d2 = “12th”; break;
case 13: d2 = “13th”; break;
case 14: d2 = “14th”; break;
case 15: d2 = “15th”; break;
case 16: d2 = “16th”; break;
case 17: d2 = “17th”; break;
case 18: d2 = “18th”; break;
case 19: d2 = “19th”; break;
case 20: d2 = “20th”; break;
case 21: d2 = “21st”; break;
case 22: d2 = “22nd”; break;
case 23: d2 = “23rd”; break;
case 24: d2 = “24th”; break;
case 25: d2 = “25th”; break;
case 26: d2 = “26th”; break;
case 27: d2 = “27th”; break;
case 28: d2 = “28th”; break;

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

public String findDay3 (int daÿ)
{
{
String d3 = null;

switch(day)
{
case 1: d3 = “1st”; break;
case 2: d3 = “2nd”; break;
case 3: d3 = “3rd”; break;
case 4: d3 = “4th”; break;
case 5: d3 = “5th”; break;
case 6: d3 = “6th”; break;
case 7: d3 = “7th”; break;
case 8: d3 = “8th”; break;
case 9: d3 = “9th”; break;
case 10: d3 = “10th”; break;
case 11: d3 = “11th”; break;
case 12: d3 = “12th”; break;
case 13: d3 = “13th”; break;
case 14: d3 = “14th”; break;
case 15: d3 = “15th”; break;
case 16: d3 = “16th”; break;
case 17: d3 = “17th”; break;
case 18: d3 = “18th”; break;
case 19: d3 = “19th”; break;
case 20: d3 = “20th”; break;
case 21: d3 = “21st”; break;
case 22: d3 = “22nd”; break;
case 23: d3 = “23rd”; break;
case 24: d3 = “24th”; break;
case 25: d3 = “25th”; break;
case 26: d3 = “26th”; break;
case 27: d3 = “27th”; break;
case 28: d3 = “28th”; break;
case 29: d3 = “29th”; break;
case 30: d3 = “30th”; break;
case 31: d3 = “31st”; break;

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

}
return d3;
}
}

public String findYear (String year)
{
String y = null;

switch(year)
{
case “00”: y = “2000”; break;
case “01”: y = “2001”; break;
case “02”: y = “2002”; break;
case “03”: y = “2003”; break;
case “04”: y = “2004”; break;
case “05”: y = “2005”; break;
case “06”: y = “2006”; break;
case “07”: y = “2007”; break;
case “08”: y = “2008”; break;
case “09”: y = “2009”; break;
case “10”: y = “2010”; break;
case “11”: y = “2011”; break;
case “12”: y = “2012”; break;
case “13”: y = “2013”; break;
case “14”: y = “2014”; break;
case “15”: y = “2015”; break;
case “16”: y = “2016”; break;
case “17”: y = “2017”; break;
case “18”: y = “2018”; break;
case “19”: y = “2019”; break;

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

return y;
}
}

And here’s the main class:

package demo3;
import java.util.Scanner;

public class DemoClass3
{
public static void main (String [] args)
{
Demo3 date = new Demo3 ();
Scanner sc = new Scanner (System.in);

System.out.println(“Please enter a number: “);
int month = sc.nextInt();

System.out.println(“Please enter a number: “);
int day = sc.nextInt();

System.out.println(“Please enter a two digit String: “);
String year = sc.next();

if (month == 4 || month == 6 || month == 9 || month == 11)
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay1(day) + ” , ” + date.findYear(year));
}

else if (month == 2)
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay2(day) + ” , ” + date.findYear(year));
}

else
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay3(day) + ” , ” + date.findYear(year));
}
}
}

And here are two sample outputs, one where the program runs as normal, and another where the default case is executed:

run:
Please enter a number:
11
Please enter a number:
27
Please enter a two digit String:
19
The date is: November 27th , 2019
BUILD SUCCESSFUL (total time: 13 seconds)

run:
Please enter a number:
11
Please enter a number:
31
Please enter a two digit String:
19
ERROR
BUILD SUCCESSFUL (total time: 6 seconds)

Alright, so the familiar thing about this program is that it is a more complicated version of the recursion example from Java Lesson 13: Recursion (the one where you enter a number and return a month). However, unlike that program, you are trying to put together a whole date using three variables-month, day, and  year.

But that’s not all. See, the month and day variables are int but the year is actually a String. Ok, so year is really a two-digit String that can range from 00 to 19 (representing 2000 to 2019). From that two-digit string, the full year is returned.

The method class has 5 methods: findMonth, findDay1, findDay2, findDay3 and findYear.  If you’ll notice from the code,  the findDay methods do the same basic thing; the only difference is that findDay1 has 30 cases, findDay2 has 28 cases, and findDay3 has 31.

As for why I made three different findDay methods, here’s a poem that explains my reasoning:

Thirty days hath September
April, June and November
All the rest have 31
Except for February which has 28

See, depending on the value for the month that the user enters, I needed three different findDay methods to handle every appropriate scenario, since not all months have the same amount of days.

And yes, I know February has a 29th every four years, but I didn’t feel like overcomplicating this program. If you tried to input a date such as February 29, 2016, you would get an error:

run:
Please enter a number:
2
Please enter a number:
29
Please enter a two digit String:
16
ERROR
BUILD SUCCESSFUL (total time: 21 seconds)

As for the two pieces of sample output shown earlier, the first piece shows the output when month=11, day=27, year="19" (that output is November 27, 2019 , the day this post was published). The second piece shows the output when month=11, day=31, year "19" (this returns an error message, since there is no such date as November 31, 2019).

Thanks for reading and Happy Thanksgiving,

Michael

Java Lesson 13: Recursion

Advertisements

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