Tabs Don’t Mean Spit – at Least in JAVA

You would think I could remember this, but I can’t. Tabs don’t mean spit – at least in JAVA!

My UIL Computer Science team was working on the following question recently:

What is the output of the following code?

a) north
b) northKorea
c) china
d) south
e) There is no output due to an error

String count="Korea";
boolean host=true;
if(count.equalsIgnoreCase("KoReA")) {
    if(host)
      out.print("north");
    else
      out.print("south");
  }
  else
    out.print("china");
    out.print(count);

The answer key shows the correct answer as being “B”. When you compile the program, you find that the answer is in-fact “B”.

We had originally reasoned that the answer would be “A” since the else condition that starts online 11 is never met. We interpreted that lines 12 and 13 would run as part of that else statement.

I have been working with Python programming in my Computer Science 1 class and anyone who has worked with Python knows that tabs are the end-all of everything.

For reference, here is what the program looks like with all of the conditionals enclosed in curly braces and tabs adjusted for readability…

class Main {
  public static void main(String[] args) {
    String count="Korea";
    boolean host=true;
    if(count.equalsIgnoreCase("KoReA")) {
      if(host){
        System.out.print("north");
      }else{
        System.out.print("south");
      }
     }else{
       System.out.print("china");
    }
    System.out.print(count);
  }
}

As you can see below, you get the same solution with the code in this configuration:

It was my mistake for not catching it, but it’s a lesson learned. As you can see, line 14 is NOT part of the else statement that starts on line 11.

Leave a Reply

Your email address will not be published. Required fields are marked *