FINDING ERROR IN THE FOLLOWING IF STATEMENT USING JAVA

E E Cummings

Total Post:26

Points:182
Posted by  E E Cummings
Java 
 1760  View(s)
Ratings:
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";
  1. Dag Hammarskjold

    Post:24

    Points:168
    Re: Finding error in the following if statement using java

    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”;
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!