shona
shona

Reputation: 101

the basic if-else statement

I'm taking the if-else statement this week and I trying to solve the question but I'm still getting an error message. Can anyone tell me what I'm doing wrong? Remember that this is an if-else question but other methods will be also appreciated.

Clunker Motors Inc. is recalling all vehicles from model years 1995-1998 and 2004-2006. Given a variable modelYear write a statement that prints the message RECALL to standard output if the value of modelYear falls within those two ranges.

if(modelYear==1995||modelYear==1998)
{
    System.out.println("Recall");   
}
else if(modelYear==2004||modelYear==2006)
{
    System.out.println("Recall");
}

Upvotes: 0

Views: 4981

Answers (4)

Preet Kukreti
Preet Kukreti

Reputation: 8617

if (modelYear==1995||modelYear==1998)

means if the year is 1995 or 1998 only. so the year 1996 and 1997 will not pass.

If you replace the statement with:

if (modelYear>=1995 && modelYear<=1998)

then you are expressing a range between 1995 and 1998 inclusive. This statement is true for only the integers [1995, 1996, 1997, 1998]. Note the switch from logical OR (||) to logical AND (&&) which means both comparison checks must be true for the conditional expression to return true.

Upvotes: 1

Azodious
Azodious

Reputation: 13882

Clunker Motors Inc. is recalling all vehicles from model years 1995-1998 and 2004-2006

it means that models from [1995, 1996, 1997, 1998] and [2004, 2005, 2006], these years should be recalled.

Your condition:

if(modelYear==1995||modelYear==1998)

means that only two years in range are counted. models from [1996 and 1997] won't be recalled.

To include both the ranges you can do following:

if ((modelYear>=1995 && modelYear<=1998) || (modelYear>=2004 && modelYear<=2006))
{
    System.out.println("Recall");
}

OR

You should create a separate method to check the ranges:

boolean isYearWithinRange(int modelYear, int start, int end)
{
    return modelYear>=start && modelYear<=end;
}

if(isYearWithinRange(modelYear, 1995, 1998) || isYearWithinRange(modelYear, 2004, 2006))
{
    System.out.println("Recall");
}

Upvotes: 1

Jugal Desai
Jugal Desai

Reputation: 164

if(modelYear>=1995 && modelYear<=1998)
{
  System.out.println("Recall");   
}
else if(modelYear>=2004 && modelYear<=2006)
{
  System.out.println("Recall");
}

Upvotes: -1

UmNyobe
UmNyobe

Reputation: 22920

You need to check for year ranges. What you are doing right now is testing for exact year values

Upvotes: 0

Related Questions