Home > DeveloperSection > Forums > Finding error in the following if statement using java
E E Cummings
E E Cummings

Total Post:26

Points:182
Posted on    October-05-2013 9:23 AM

 Java Java 
Ratings:


 1 Reply(s)
 1369  View(s)
Rate this:

Find the error in the following if statement that is intended to select a language for a given country and state/province. (5 points)

language = "English";
if (country.equals("Canada"))
    if (stateOrProvince.equals("Quebec"))
         language = "French";
    else if (country.equals ("China"))
language = "Chinese";


Dag Hammarskjold
Dag Hammarskjold

Total Post:24

Points:168
Posted on    October-05-2013 9:33 AM

Braces are important. Your code actually gets executed as

if (country.equals(“Canada”)) {
  if (stateOrProvince.equals(“Quebec”)) {
    language = French”;
  } else if (country.equals (“China”)) {
    language = Chinese”;
  }
}

So, your country.equals("China") block would never get executed because within that block country.equals("Canada") is already true. Rewrite your code with proper braces as

if (country.equals(“Canada”)) {
  if (stateOrProvince.equals(“Quebec”)) {
    language = French”;
  }
} else if (country.equals (“China”)) {
  language = Chinese”;
}

Don't want to miss updates? Please click the below button!

Follow MindStick