// Miya Natsuhara // 07-10-2019 // CSE142 // TA: Grace Hopper // Provides some short examples of writing methods that return values, and using the Math class. /* DEVELOPMENT NOTES: ((Note: this is not something you should include in your own programs; this is included here to aid in your understanding and to provide additional context for the program.)) This was our introduction to returns and the Math class. Remember, there are three parts to a method that returns: - return statement - return type in the method header - catch/use the value where the method is called Also recall that you can only return *one* thing from a method, and as soon as a return statement is reached, the method is immediately exited. Look at the returnExample method for an example of this. */ public class ReturnPractice { public static void main(String[] args) { int x = 8; int y = -4; int max = Math.max(x, y); System.out.println("max is " + max); // minimum dating age: take age, divide by 2, add 7 // max dating age: take age, subtract 7, multiply by 2 // int minDatingAge = 21 / 2 + 7; int minDatingAge = calcMinDatingAge(21); System.out.println("min dating age for 21 is: " + minDatingAge); int maxDatingAge = calcMaxDatingAge(21); System.out.println("max dating age for 21 is: " + maxDatingAge); // int minDatingAge2 = 19 / 2 + 7; int minDatingAge2 = calcMinDatingAge(19); System.out.println("min dating age for 19 is: " + minDatingAge2); int maxDatingAge2 = calcMaxDatingAge(19); System.out.println("max dating age for 19 is: " + maxDatingAge2); } // Computes and returns the minimum dating age for the given age. // int age: the age for which we compute the minimum dating age public static int calcMinDatingAge(int age) { int minDatingAge = age / 2 + 7; return minDatingAge; } // Computes and returns the maximum dating age for the given age. // int age: the age for which we compute the maximum dating age public static int calcMaxDatingAge(int age) { return (age - 7) * 2; } // Always returns 0 public static int returnExample() { /* Because the method is exited as soon as a return statement is reached, the first time the for loop body is executed (when i is 0), i is returned and the method is exited. However, note that if we changed the for loop test to be 'i > 5', then -1 would be returned because the for loop's test would never pass and so the body of the for loop would never run. */ for (int i = 0; i < 5; i++) { return i; } return -1; } }