简体   繁体   中英

how do I compare elements of an array with a scalar value

How do I compare elements of an array with a scalar value?

Here is the portion of code with the error:

if(month != numMonth[])
    System.out.printf("\n not a valid month");
if (day != daysInMonth[]  &&  day> daysOfMonth[month])
    System.out.printf("\n not a valid day");
if (year<1880 && year>2280)
    System.out.printf("\n not a valid year");

In (day != daysInMonth[] && day> daysOfMonth[month]) expr I get a class file expected error.

Use

if (month < 0 || month > 11)

or

if (month < 1 || month > 12)

depending on whether the numbering starts from zero or from one.

&c

You can compare an element of an array with a scalar, not the entire array. Also the syntax you're using is only valid at declaration time:

int numMonth[] = new int[10];
or 
int numMonth[] = {1,2,3};

and so on

To compare to a single scalar you need to reference the element you want to compare it to:

// to compare with the 1st entry
numMonth[0] == month; // with arrays being zero based
// to compare with the 2nd entry
numMonth[1] == month;

and so on

I'm going to suggest a simpler alternative (IMHO).

For this task, I'd use the Calendar class directly, to avoid storing the different days and years in an array. Leap years can be an issue in particular situations here.

First of all, validate the years. They're the simplest of validations in this chain and, like them months, they do not depend on any of the successive parameters entered. The last check you do, becomes the first in this case:

if (year < 1880 && year > 2280)
    System.out.printf("\n not a valid year");

After validating the year, validate the months. They're also a simple number but you have to define how do you manage them. I'll take the range 1 -> 12 :

if(month < 1 || month > 12)
    System.out.printf("\n not a valid month");

Finally, you build up a date with the help of a Calendar . This way you can obtain the correct amount of days that correspond to a certain month. Then, you validate accordingly.

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); //Calendar manages the months 
                                    //from 0 to 11, that's why 
                                    //you need to substract 1
int maxDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

maxDays contains the max amount of days for the given month and year. Now, you only have to check id the input for the day is in the range:

if (day < 1 || day > maxDays)
    System.out.printf("\n not a valid day");

This way, you don't need to keep a track of the days for each month, and you also manage leap years.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM