This advanced control material is drawn from earlier chapters in the text.
Reading:
Consider the following code segments. Can you effectively re-write them using a
switch
statement? If so demonstrate how and consider whether the
switch
-based version is better or worse than the
if
-based version version. If not, explain why not.
The following code segment converts an integer entered by the user into a word, e.g., it converts 1 to “one”.
Scanner keyboard = new Scanner(System.in); System.out.print("Enter a digit between 0 and 4: "); int x = keyboard.nextInt(); if (x == 0) { System.out.println("zero"); } else if (x == 1) { System.out.println("one"); } else if (x == 2) { System.out.println("two"); } else if (x == 3) { System.out.println("three"); } else if (x == 4) { System.out.println("four"); } else { System.out.println("invalid input..."); }
The following code segment converts a word entered by the user into a digit, e.g., it converts “one” to 1.
System.out.print("Enter a digit name (i.e., one, two, ..., four): "); String number = keyboard.next(); if (number.equalsIgnoreCase("zero")) { System.out.println(0); } else if (number.equalsIgnoreCase("one")) { System.out.println(1); } else if (number.equalsIgnoreCase("two")) { System.out.println(2); } else if (number.equalsIgnoreCase("three")) { System.out.println(3); } else if (number.equalsIgnoreCase("four")) { System.out.println(4); } else { System.out.println("invalid input..."); }
Try converting the factorial function shown in the text into a similar summation function, that is
computeSummation(n)
returns:
1 + 2 + ... + n.
Yes, we know that this can be computed without repetition using
n(n-1)/2
, but pretend that you don’t know that!