Skip to content

Instantly share code, notes, and snippets.

@speters33w
Created April 5, 2022 20:37
Show Gist options
  • Save speters33w/63c4ee9df6a019555023703b02bcb45e to your computer and use it in GitHub Desktop.
Save speters33w/63c4ee9df6a019555023703b02bcb45e to your computer and use it in GitHub Desktop.
Feet and Inches to Centimeters Java Method Overloading Sample
public class FeetAndInchesToCentimeters {
//This is a sample of Java Method overloading.
//My solution to a challenge from Udemy Java Programming Masterclass covering Java 11 & Java 17
//by Tim Buchalka Lecture 58.
public static void main(String[] args) {
System.out.println(FeetAndInchesToCentimeters.calcFeetAndInchesToCentimeters(5,10));
System.out.println(FeetAndInchesToCentimeters.calcFeetAndInchesToCentimeters(4,10));
System.out.println(FeetAndInchesToCentimeters.calcFeetAndInchesToCentimeters(70));
System.out.println(FeetAndInchesToCentimeters.calcFeetAndInchesToCentimeters(58));
}
public static int calcFeetAndInchesToCentimeters(int feet, int inches) {
if(feet<0||inches<0||inches>=12){
return -1;
}
double centimeters = ((feet*12) + inches) * 2.54;
return (int)Math.round(centimeters);
}
public static int calcFeetAndInchesToCentimeters(int inches) {
if(inches<0){
return -1;
} else {
int feet = (inches / 12);
inches = (inches % 12);
double centimeters = calcFeetAndInchesToCentimeters(feet,inches);
return (int)Math.round(centimeters);
}
}
}
// Create a method called calcFeetAndInchesToCentimeters
// It needs to have two parameters.
// feet is the first parameter, inches is the 2nd parameter
//
// You should validate that the first parameter feet is >= 0
// You should validate that the 2nd parameter inches is >=0 and <=12
// return -1 from the method if either of the above is not true
//
// If the parameters are valid, then calculate how many centimetres
// comprise the feet and inches passed to this method and return
// that value.
//
// Create a 2nd method of the same name but with only one parameter
// inches is the parameter
// validate that its >=0
// return -1 if it is not true
// But if its valid, then calculate how many feet are in the inches
// and then here is the tricky part
// call the other overloaded method passing the correct feet and inches
// calculated so that it can calculate correctly.
// hints: Use double for your number dataTypes is probably a good idea
// 1 inch = 2.54cm and one foot = 12 inches
// use the link I give you to confirm your code is calculating correctly.
// Calling another overloaded method just requires you to use the
// right number of parameters.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment