I need to verify that the number the user inputed is between 1908 and 2012. here are the actual instructions

"The constructor must also verify that the value provided for "year" is at least 1908 and at most 2012 – if not, set the year to 2010 by default"

I was think along the lines of this

``````if (y >= 1980 && y<= 2010)
{    y=year;     }
if (y<1980 || y>2012)
{
y=2010;
}``````

or

``````if (y >= 1980 && y<= 2010)
{
y=year;
}

else
{
y=2010;
}``````

All 7 Replies

If "year" is the value to check then that, of course, is the value you need to use in the if statement. In any case, the second version is the one to use, as long as you are checking the right value and actually check for 2012, not 2010.

Note that the instructor asks to verify the value provided for "year" is at least 1908 and at most 2012, hence the code should be:

``````if (y >= 1980 && y<= 2012)
year=y;
else
year=2010;``````

The following code by using ternary operator is also valid:

``year = ( y>=1980 && y<=2012)? y : 2010;``

Please, do not attempt to teach "newbies" the ternary operator, and please, also, do not teach them not to use braces ({}) in an if statement (or for/while loops, etc). It is always safer to use braces and both of these things will do nothing but confuse "newbies" at this point.

Just an attempt at constructive criticism.

P.S. The "value" to check (whether year or y) will, of course, depend on how the rest of the code is written. Now, whether or not those used names correspond to the implied names in the assignment description is another matter.

Lxyslckr,
As masijade indicates, one should use the second version.
May I indicate some errors in the second version?
line 1 should be
if (y >= 1980 && y<= 2012)
line 3 should be
year = y;
line 8 should be
year = 2010;

if(1908<=y && 2012>=y)
{
year=y;
}
else
{
year=2010;
}

this is Good coding style!!
bcoz if u misplace "==" with "=" the program gets wrong.