public class Main

public static void main(String[] args) {
 double centimeters = calcFeetAndInchesToCentimeters(5, 11);
 if (centimeters < 0.0) {
 System.out.println("Invalid parameters");
 }

calcFeetAndInchesToCentimeters(71);
 }

public static double calcFeetAndInchesToCentimeters(double feet, double inches) {
 if ((feet < 0) || ((inches < 0) || (inches > 12))) {
 System.out.println("Invalid feet or inches parameters");
 return -1;
 }

double centimeters = (feet * 12) * 2.54;
 centimeters += inches * 2.54;
 System.out.println(feet + " feet " + inches + " inches = " + centimeters + " cm");
 return centimeters;
 }

public static double calcFeetAndInchesToCentimeters(double inches) {
 if (inches < 0) {
 return -1;
 }

double feet = (int) inches / 12;
 double remainingInches = (int) inches % 12;
 System.out.println(inches + " inches is equal to " + feet + " feet and " + remainingInches + " inches");
 return calcFeetAndInchesToCentimeters(feet, remainingInches);
 }
 }

I’ve been studying java online and this is the first code I’ve done that I’ve been excited about. The tutorial was about method overloading. I’ll try to explain how it works.

There is the “main” class and method, which is what runs if you click run.

The main method contains a double-type variable called centimeters. This variable is referenced in various sentences that are printed out.

There is a method called calcFeetAndInchesToCentimeters which accepts feet and inches as variables. This contains an if statement to do validation. If it doesn’t meet the criteria is prints an error message and returns -1, which is used by the above method.

The next method calculates the number of centimeters in the number of feet and inches given. It updates the centimeters variable, prints out the value given and returns the centimeters variable.

It then overloads the calcFeetAndInchesToCentimeters method bu doing it again with only one parameter. This method does an validation on the number of inches, returning -1 if it doesn’t meet the criteria.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s