// This program is flawed in several ways. It calls update methods that // manipulate a local copy of a variable n without updating the value of n, it // uses the wrong if/else structures, and it has redundant code that can be // factored. import java.util.*; public class BadIfReturn { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("give me an int-> "); int n = console.nextInt(); update(n); System.out.println("updated n = " + n); System.out.println(); update2(n); System.out.println("updated n = " + n); } // This method updates the value of n. It is supposed to either add one to // n (for negatives), reset n to 1000 (for 0), or subtract 1 from n (for // positives). Because it uses the wrong if/else structure, it potentially // performs multiple updates public static void update(int n) { if (n < 0) { n++; } if (n == 0) { n = 1000; } if (n > 0) { n--; } } // This method performs a "special" update that either adds 42 to n (for // negatives) or subtracts 13 from n (for non-negatives). public static void update2(int n) { if (n < 0) { System.out.println("special update in progress"); int change = 42; n = n + change; System.out.println("updated by " + change); } else if (n >= 0) { System.out.println("special update in progress"); int change = -13; n = n + change; System.out.println("updated by " + change); } } }