PROBLEM #1: Determine if a number is between 0 and 25, 26 and 50, or greater than 50.
int x = 75;

if (x > 50) {
  println(x + " is greater than 50!"); 
} else if (x > 25) {
  println(x + " is greater than 25!");
} else {
  println(x + " is 25 or less!");
}	
OUTPUT: “75 is greater than 50!”
int x = 75;

if(x > 25) {
  println(x + " is greater than 25!"); 
} else if (x > 50) {
  println(x + " is greater than 50!");
} else {
  println(x + " is 25 or less!");
}
OUTPUT: “75 is greater than 25!”

Although the syntax is correct, what is problematic about the code in part 2 above?

Answer: Notice how the order of the conditional statement matters. In part 2, “x is greater than 50″ will never be printed b/c anything greater than 50 is also greater than 25!


PROBLEM #2: If a number is 5, change it to 6. If a number is 6, change it to five.
int x = 5;
println("x is now: " + x);
if (x == 5) {
  x = 6;
}
if (x == 6) {
  x = 5;
}
println("x is now: " + x);
OUTPUT: “x is now 5. x is now 5″
int x = 5;
println("x is now: " + x);
if (x == 5) {
  x = 6;
} else if (x == 6) {
  x = 5;
}
println("x is now: " + x);
OUTPUT: “x is now 5. x is now 6″

Although the syntax is correct, what is problematic about the code in column 1 above?

Answer: Without an “else if” both “if” statements are running, and so x changes to 6 and then back to 5 again instead of only changing to 6.


»

No comments yet.

Leave a comment