// This is a variation of the BadIfReturn program that fixes the problems. It // uses return values to update the value of n in main and it uses proper // if/else structures and eliminates redundancy by factoring the if/else // construct in update2. import java.util.*; public class GoodIfReturn { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("give me an int-> "); int n = console.nextInt(); n = update(n); System.out.println("updated n = " + n); System.out.println(); n = update2(n); System.out.println("updated n = " + n); } // This method updates the value of n by either adding one to n (for // negatives), resetting n to 1000 (for 0), or subtracting 1 from n (for // positives). It returns the updated value of n. public static int update(int n) { if (n < 0) { n++; } else if (n == 0) { n = 1000; } else { // n > 0 n--; } return n; } // This method performs a "special" update that either adds 42 to n (for // negatives) or subtracts 13 from n (for non-negatives). It returns the // updated value of n. public static int update2(int n) { System.out.println("special update in progress"); int change; if (n < 0) { change = 42; } else { change = -13; } n = n + change; System.out.println("updated by " + change); return n; } }