R Lesson 32: Basic Trigonometry, R Style

Hello everybody,

So far this year, we’ve explored the basics on making our own Python game with the pygame module-pretty cool right! After all, it was the first time this blog delved into game development.

However, building a good game takes time; this includes the BINGO game we’ve been developing. With that said, I’ll need to spend a little more time fine-tuning the BINGO game and planning out the game development series going forward. I’d hate to go too long without keeping fresh content on this blog, so with that in mind, in today’s post, we’ll explore something a little different-R trigonometry (you may recall I did a number of R mathematics posts last year)

Last year, we explored some basic R calculus-this year, we’ll explore basic R trigonometry. For those who don’t know what I’m talking about, trigonometry is a branch of mathematics that deals with the study of triangles and their angles.

Trigonometry basics

Before we get into the fun of exploring trig with R, let’s explore some basic trigonometry terms using this handy-dandy illustration:

Here we have a simple right triangle with a 90 degree angle, a 52 degree angle, and a 38 degree angle along with two sides of lengths 10 and 7 and a hyptoensue of length 12.2 (remember the Pythagorean theorem for right triangles-to find the length of the hypotenuse, a squared + b squared = c squared).

If you’ve ever taken at least precalculus with basic trigonometry, you’ll certainly recognize the mnemonic on the upper-right hand corner of the screen-SOHCAHTOA. If you’re not familiar with this mnemonic, here’s what it means:

  • SOH: To find the sine of an angle in the triangle, take the ratio of the length of the side opposite the angle to the length of the hypotenuse
  • CAH: To find the cosine of an angle in the triangle, take the ratio of the length of the side adjacent to the hypotenuse to the length of the hypotenuse
  • TOA: To find the tangent of an angle in the triangle, take the ratio of the length of the side opposite to the hypotenuse to the length of the side adjacent to the hypotenuse

Trigonometry, R style

Now that we’ve discussed the basics of trigonometry, let’s discuss trigonometry, R style. Here are some examples of the three basic trigonometric functions executed in R:

> cos(20)
[1] 0.4080821
> tan(20)
[1] 2.237161
> sin(20)
[1] 0.9129453

In this example, I used R’s built-in cos(), tan() and sin() functions to calculate the cosine, tangent, and sine of a given angle, respectively. Since these functions are built-in to R, there’s no need to install any extra packages to utilize these functions

You may be wondering if these functions can calculate the sine/cosine/tangent of an angle given specific side lengths (as shown in the illustration above). The answer to that is no, but then again, you can easily calculate these trigonometric ratios using simple division. For instance, in the illustration above, the sine of the 52 degree angle in the triangle is ~0.82 (rounded to two decimal places) because the opposite/hypotenuse length ratio is 10/12.2.

So, how does R calculate trigonometric ratios of certain angles? They use a little something called radians, which I’ll explain more right here.

Radians

What are radians, exactly? Well, when measuring angles in shapes, there are two metrics we use-degrees (which I’m sure you’re familiar with) and radians.

Let’s take this illustration of a circle:

As you see, the length of this circle’s radius is 8-the arc of the circle that is formed also has a length of 8. Therefore, the angle that is formed at the circle’s center has a length of 1 radian.

Now, how do you convert radians to degrees. Easy-1 degree is equal to pi/180 radians.

Why are radians expressed as a ratio of pi? This is because, for one, the circumference of a circle is 2pi times the circle’s radius. For two, the length of a full circle is 360 degrees-or 2pi radians; similarly, the length of a half-circle is 180 degrees-or pi radians.

Now, let’s analyze how radians work in the context of our R examples (all of which used 20 degree angles).

I mentioned earlier that 1 degree equals pi/180 radians, so 20 degrees would be 20*(pi/180) radians, which when converted to simplest form, equals pi/9 radians, which is then used to calculate various trigonometric ratios for any given angle.

The degrees-to-radians formula is so versatile that in R, it can be used on any integer, positive or negative. Check out some of these examples:

> cos(-3)
[1] -0.9899925
> sin(355)
[1] -3.014435e-05
> tan(15000)
[1] -1.98891
> cos(412)
[1] -0.8998537
> sin(-1333)
[1] -0.8218865
> tan(10191)
[1] -0.338695

Yes, I can use R’s basic trigonometric functions on a wide variety of integers and obtain valid results from each integer (although let’s be real, where will you ever find a 15000 degree angle)?

Thanks for reading,

Michael

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

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 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

 

 

Python Lesson 4: Math & Logic

Hello everybody,

It’s Michael, and today’s lesson will be on Python math and logic, with an emphasis on mathematical and logical operators in Python.

First, we’ll start off with mathematical operators. Python has seven mathematical operators, which include +, -, *, /, %, ** and //. If you know Java (or basic arithmetic for that matter), then the first four operators would look very familiar to you, since they are the addition, subtraction, multiplication, and division operators, respectively.

However, let’s discuss the other three operators-%, **, and //. % is the modulo operator, which is what we would use for modular division. For those unfamiliar with the concept, modular division is similar to regular division, except you are trying to find the remainder of two numbers instead of the quotient. For instance, 11%4 (read as 11 mod 4) is 3, since 11 divided by 4 is 2 with a remainder of 3.

** is the exponentiation operator. This one is pretty simple to explain, since this would be the operator you would use if you want to raise a number to a certain power. That’s all. For example, 8 cubed in Python would be 8**3. This is much simpler than using Java’s Math.power() function (which requires importing a class-not the case with Python).

// would probably look the most unfamiliar to you (I had to look it up the first time I saw it). This is the floor division operator, and I’ll admit that, even though I do lots of coding, I’ve never heard of the concept of floor division. Apparently, floor division is a very simple concept, as it is regular division with any decimal points removed from the quotient. However, keep in mind that floor division rounds DOWN to the nearest integer, so in a division problem like 20/7 with a simple division quotient of 2.86 (rounded to two decimal places), the floor division quotient would be 2, not 3.

Another thing to keep in mind with floor division is that, if either the dividend or divisor is negative, the quotient will also be rounded down, but it will be rounded away from 0 NOT towards 0. For example, -20/7 has a simple division quotient of -2.86 but a floor division quotient of -3, not -2. So when I say a negative floor division quotient would be rounded away from 0, I mean that the quotient will be rounded to the LOWER negative number, not the higher negative number.

Now, let’s see the %, **, and // operators in action:

a = 30 % 8
b = 6**3
c = 177 // 33
print(a)
print(b)
print(c)

And here’s the output:

6
216
5

The answer for a-6-is displayed first. 30 mod 8 is 6, meaning that 30 divided by 8 will give you a remainder of 6. The answer for b-216-is displayed next. 6 cubed is 216. The answer for c-5-is displayed last. The simple division quotient (rounded to two decimal places) is 5.36, so the floor division quotient is rounded down to 5.

Now let’s demonstrate some PEMDAS (remember this?) in Python:

a = 4 – (2 + 5) * 11 / 2
print(a)

And here’s the output:

-34.5

OK, so this is a simple enough problem. Parentheses come first, so (2+5) would be solved first; you would get a result of 7. 7 would then be multiplied by 11 to get 77, which would then be divided by 2 to get 38.5, which would be subtracted from 4 to get the final result of -34.5.

Now let’s try something a little more complex:

a = 100 // (16 + 2) – 31 + 3**4 / (6 * 12) * 15 % 6
print(a)

And here’s the output:

-21.125

Here’s a breakdown showing how to get to the final answer:

  • 100 // (16 + 2) - 31 + 3**4 / (6 * 12) * 15 % 6
  • 100 // 18 - 31 + 3**4 / 72 * 15 % 6
  • 100 // 18 - 31 + 81 / 72 * 15 % 6
  • 5 - 31 + 1.125 * 15 % 6
  • 5 - 31 + 16.875 % 6
  • 5 - 31 + 4.875
  • -26 + 4.875
  • -21.125

Keep in mind that with order of operations in Python, the % and // operators are treated with the same precedence as the simple division operator (/).

Next, I’ll cover comparison operators, which are used to compare two values. There are 6 comparison operators in total-==, !=, >, <, >=, <=, which respectively represent:

  • Equal to
  • Not equal to
  • Greater than
  • Less than
  • Greater than or equal to
  • Less than or equal to

Statements with these logical operators will either return true or false. Let’s demonstrate the comparison operators:

a = (13 + 11) == 24
b = (41 + 16) != 66
c = (15 > 29)
d = (41 < 23)
e = (13 >= 9)
f = (55 <= 22)
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)

And here’s the output:

True
True
False
False
True
False

So, in order, here’s the result for each statement:

  • a-TRUE
  • b-TRUE
  • c-FALSE
  • d-FALSE
  • e-TRUE
  • f-FALSE

The next thing I wanted to discuss are the three logical operators-and,or, and not. The logical operators work just as they do in Java, except in Python, you would words instead of the symbols &&, ||, and !-which are and, or, and not, respectively. However, the logic behind these operators is the same as in Java. By this I mean:

  • For two statements combined with and, both of the individual statements must be true for the statement pair to be true. If one of the statements is false, then both are false.
  • For two statements combined with or, only one of the statements must be true for the statement pair to be true. However, if both statements are false, then the whole statement pair is false.
  • Statement pairs with not often contain an and or or as well (e.g. not(statement pair a or statement pair b)). The statement pair in parentheses would first be evaluated, and the result would be whatever the opposite of the result from the statement pair. For instance, if the statement pair was true, then (assuming there is a not), the result would be false, and vice versa.

Let’s start with a simple demonstration of logical operators:

m = (14 > 19) and (15 + 12 != 33)
o = (51 >= 16) or (9 – 2 > 6)
f = not(14**2 < 28 and 13 % 9 <= 1)
print(m)
print(o)
print(f)

And here’s the output:

False
True
True

The results to each statement are:

  • m-FALSE
  • o-TRUE
  • f-TRUE

Now, let’s try something slightly more complex with logical operators:

m = (14 < 19) and (23 >= 11) or (100 % 16 > 7)
print(m)

And here’s the output:

True

How did we get this result? First of all, keep in mind that the statement pairs will be evaluated from left to right (just as they would in order of operations problems). The result of the first statement pair-(14 < 19) and (23 >= 11)-is true, so that result would be evaluated with the second statement-(100 % 16 > 7)-which is also true. Since we are dealing with two trues and an or, the entire statement group is true.

Next, we’ll discuss the two identity operators-is and is not-which also function as comparison operators. However, these operators don’t evaluate whether or not two objects are equal or not; rather, these operators test whether or not two values are the same object with the same memory location. I know that sounds like a lot of coding jargon, so here’s a program to demonstrate identity operators:

a = (“ant”,”bear”,”cat”,”dog”,”eel”)
b = (“ant”,”bear”,”cougar”, “dog”, “eel”)
print(a is b)
print(a is not b)

And here’s the output:

False
True

A simple way to explain this program is that I’m trying to test whether a and b have the exact same values. The first statement-a in b-is false because a and b do not have the exact same values. However, the second statement-a not in b-is true because a and b do not have the exact same values.

An easy way to remember identity operators is that, when comparing two lists, is means the two lists are exactly alike while is not means that the two lists aren’t exactly alike.

Finally, let’s cover the concept of membership operators. Like identity operators, there are two membership operators-in and not in-and both identity and membership operators are used with lists. Here’s a program demonstrating identity operators:

a = (“carrot”, “celery”, “squash”, “cucumber”, “eggplant”)
print(“squash” in a)
print(“squash” not in a)

And here’s the output:

True
False

In this program, I am testing whether or not squash is in my list (a). Just as with the previous program, I used both possible operators-in and not in-to see which one would give me true and which would give me false. The first statement-squash in a-is true, meaning that squash is in list a. Thus, the second statement-squash not in a-is false.

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 5: Java Numbering Systems

Hello everybody,

It’s Michael, and today’s lesson will be a little different. There won’t be actual coding involved here, rather, I will discuss a topic which is important in Java-numbering systems.

What’s the point of numbering systems? Think of this way-we communicate with each other with words and numbers, but since computers only understand numbers, numbers are how computers communicate with each other. When we enter data in our programs, that data is converted into electronic pulse, which is then converted into numeric format by ASCII (an acronym for American Standard Code for Information Interchange), which is the system used for encoding characters (whether 0-9, A-Z lowercase or uppercase, or some special characters like the backslash and the semicolon) based off the four main numbering systems (binary, octal, hexadecimal, and decimal). Each character, of which there are 128, has their own unique ASCII value for each of the four numbering systems.

Now, let’s explain each of these four numbering systems:

  • Binary is a base-2 number system, as there are only two possible values-0 and 1. 0 represents absence of electronic pulse while 1 represents presence of electronic pulse. A group of four bits, like 1100, is called a nibble while a group of eight bits, like 01010011, is called a byte. The position of each digit in a group of bits represents a certain power of 2.
    • To find out the decimal form of 01010011, multiply each 0 and 1 by a power of 2. You can determine which power of two to use based on the position of the 0 or 1 in the group. For instance, the 1 at the end of the group would be multiplied by 2^0, since you would always start with the power of 0. Then work your way left until you reach the last bit in the group (and increase the exponent by 1 each time).
    • The number in decimal form is 83, which can be found through this expression (2^0+2^1+2^4+2^6). Granted, you don’t need to worry about the 0 bits, since 0 times anything is 0. And for the 1 bits, you just need to calculate the powers of two and add them together; don’t worry about multiplying 1 to each power since 1 times anything equals itself.
    • And remember to ALWAYS start with the power of 0 and work your way left, increasing the exponent by 1 each time.
  • Octal is very similar to binary, except it is a base-8 system, so there are 8 possible values-0 to 7 (Java tends to like to start with 0).
    • Octal-to-decimal conversions are very much like binary-to-decimal conversions, except you’re dealing with successive powers of 8 as opposed to powers of 2.
    • Take the number 145. What would this be in decimal form?
    • If you said 101, you’re right. You can find this out using the expression (1*8^2+4*8^1+5*8^0). Remember to multiply each digit by their respective power of 8, then find the sum of all the products.
    • And ALWAYS remember to start with the power of 0.
  • Decimal is the number system we use every day when talking about numbers; it is a base-10 system, so there are ten possible values (0 to 9). You are probably very familiar with this system, so there’s not much explaining to do here.
  • Hexadecimal is an interesting system for a few reasons. First of all, it is a base-16 system, so there are 16 possible values. Secondly, this is the only alphanumeric system of the four I discussed, as this system uses the digits 0-9 and the letters A-F which represent the numbers 10-15.
    • Hexadecimal-to-decimal conversions follow the same process as octal-to-decimal and binary-to-decimal conversions, except you’re dealing with successive powers of 16.
    • What do you think 45ACB could be in decimal form?
    • If you answered 285,387, you’re right. Here’s the expression: (4*16^4+5*16^3+A*16^2+C*16^1+B*16^0). Remember that A is 10, B is 11, C is 12, D is 13, E is 14, and F is 15.

Remember that these four systems aren’t the only possible number systems, as there are other number systems for several different bases. For instance, a base-4 system would use the numbers 0-3 and utilize successive powers of 4 in conversions. Here’s some things to know about other number systems:

  • Base-X means that there are X possible values (so base-9 would have 9 possible values)
  • The starting point for number systems is always ZERO; the endpoint is X-1 (so 5 would be the endpoint for a base-6 system)
  • You would convert base-X numbers to decimal form utilizing successive powers of X (so trying to convert a number in base-5 decimal form would utilize successive powers of 5-5^0, 5^1, and so on), multiplying each digit by the power of X, and finding the sum of all the products.
  • When the base is greater than 10, use letters of the alphabet for values above 9. So for base-19, use the letters A-I for the values 10-18.

Now, here are some conversion problems for you. Can you solve them? I will post the answers on the next post:

Binary-to-decimal

  • 0110
  • 10011
  • 1100001
  • 1001001

Octal-to-decimal

  • 523
  • 3455
  • 123023
  • 2346523

Hexadecimal-to-decimal

  • 4BF
  • 67AC
  • AF12
  • 192DCC

Thanks for reading,

Michael

Java Lesson 3: User Input, Importing Classes, and Java Math

Hello everybody,

It’s Michael, and today’s post will be on user input, importing classes, and doing math in Java. I know these may seem like three totally unrelated topics, but I think they relate well to one another, which is why I’m going to cover all of them in this post.

First off, let’s discuss how to manage user input in your Java program. If you weren’t already aware, Java output doesn’t always have to be predefined-you can write your code so that you can choose the output.

The first thing you would need to do is import the Scanner class from Java, which is the class that handles all text input (don’t think about using it for graphics-heavy programs). Importing the Scanner class (or any class for that matter) allows you to use all its methods.

Here’s an example of a Scanner program:

19jan capture1

The first thing I did was to import the Scanner class. I then created s, which is a variable of type Scanner. Remember to always create a Scanner variable every time you want to use the Scanner class in your program! And remember to ALWAYS set the parameters as (System.in).

I then used System.out.println to write the command asking the user for their input.  The user’s input then is stored in a variable, in this case int year. You must always store your input in a variable if you want it to display on the screen. What variable type you choose depends on what kind of input you are seeking. In this case, since I am seeking integers, I want to use type int. The value you assign to the variable would be (name of Scanner variable).next(type of variable your input is). Since my Scanner variable is named s and my input variable is of type int, the value I assigned my variable was s.nextInt(). The next______ method you use depends on the input variable’s type, so if I had a char variable I would use s.nextChar(). Please note that there is no nextString method so for String variables use next or nextLine.

For those who would like a video demonstration of the Scanner class, check out this program-Scanner demo.

Now, Scanner isn’t the only class you can import from Java. In fact there are plenty of other classes (and methods) you can use and import for a variety of purposes, such as the class Calendar for calendar programs. The best part is that you don’t need to memorize all of the classes available on Java, as there is a handy online dictionary where you can look up classes and methods that you need for your program. This dictionary does a very good job of explaining how you can use each available class.

Now at the beginning of this post, I said I was going to cover how to do math in Java. Well, there is a certain class that I will show you how to use to do just that-it’s the Math class. To access this class, use the line import java.lang.Math. Here are three programs utilizing the Math class and its methods.

20jan capture

This program asks the user for a negative number, then finds the absolute value of that number. Since I typed -33, the program calculated 33 as the absolute value.

20jan capture2

This program asks the user for two numbers, then will calculate the value of the first number raised to the power of the second number. Since my first number was 9 and my second number was 3, the program printed out 729, or 9 cubed (which is a more colloquial way of saying “to the third power”)20jan capture3

This last program asks the user for a number, which in this context is an angle measurement for a right triangle. The program will then display the cosine (recall SOHCAHTOA) for that angle measurement; since I used a 49 degree angle in this example, the cosine is  0.3006 (rounded to four decimal places).

However, one thing to note is that the Math is more geared towards complex mathematical operations (like finding logs, trigonometric ratios, and square roots). You don’t need the Math class for basic arithmetic.

In case you’re wondering, here are two programs showing how to do basic arithmetic in Java:

21jan capture1

This program demonstrates simple division; the user is asked for a number divisible by 3, then the program will print out the quotient of that number divided by 3. Since I used 612, the quotient displayed was 204.

21jan capture2

This program utilizes the order of operations (think PEMDAS); the user is asked to type in a number and the program will print out the answer to the problem (pemdas/2)*3+8-4. Remember pemdas is the name of the variable where you will store the number you choose. I chose to store the user input as a double because I wanted a precise answer; had I stored the input as int , I would’ve gotten the nearest whole number (12) instead of the more precise answer I wanted-11.5.

  • Something I should have pointed out earlier-ALWAYS remember to put semicolons after each statement! To be clear, this only means the lines of code inside each method or class along with any import statements. This doesn’t mean semicolons are needed after class/method declarations themselves!
  • This isn’t totally necessary when coding, but the // symbol right before a line of code is a way to take notes within your program. The compiler won’t read any line of code that begins with //.

Now before I go, here’s a video demonstration on doing math in Java (both with the Math class and without)-Java Math.

Thanks for reading,

Michael