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

Edited 6 Years Ago by Lxyslckr: n/a

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;

Edited 6 Years Ago by tong1: n/a

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.
so please use like this style if(1980==y) instead of if(y==1980)
so that an error will be thrown by compiler if u forget "=" in if() and easy to debug!!
all the best!!

In most languages that might be good advice, but it is a bit unnecessary in Java. In Java using = in an if statement (except in special circumstances and never as the "boolean" operator) will cause a compile error that you must fix before the program will compile, so it is not quite as "important" (or maybe "relevant" is a better word) in Java.

Thank you everyone. It was really bugging me. I still have some bugs to work on but I think someone must have had the same error so I'm going see if I can find a similar solution.

This question has already been answered. Start a new discussion instead.