2

I'm trying to find an integer inside of an int[] array and return true or false depending on whether or not it's present anywhere, however my code, which I've taken from numerous websites.

My array is as follows:

private static final int[] thirtyOneDays = {1, 3, 5, 7, 8, 10, 12};

And I'm searching it like so:

Arrays.asList(thirtyOneDays).contains(month)

Where month is an integer.

When debugging the program all the variables and fields are set correctly as expected, it just always returns false. Does anyone know why this is?

As for month, it originates from a JTextField on my GUI:

new Validate(txtDay.getText(), txtMonth.getText(), txtYear.getText());

Here's the Validate constructor:

public Validate(String day, String month, String year)
{
    instance = this;

    if(this.isYearValid(year))
    {
        if(this.isMonthValid(month, year))
        {
            if(this.isDayValid(day, month, year))
            {
                isAllValid = true;
            }
        }
    }
}

And here's the very top of isDayValid():

private boolean isDayValid(String dayS, String monthS, String yearS)
{
    int year = Integer.parseInt(yearS);
    int month = Integer.parseInt(monthS);
    int day = Integer.parseInt(dayS);

~~~~~~~ P.S. What's the difference between:

int[] intArray = {1, 2, 3}
int[] intArray = new int{1, 2, 3, 4}
Integer[] intArray = new Integer{1, 2, 3, 4}
Jake Stanger
  • 449
  • 1
  • 8
  • 24

4 Answers4

3

Arrays.asList(thirtyOneDays) returns a List containing a single entry of type int[] which is different from any of the integers in the original List.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

Try this instead:

    for(int x:thirtyOneDays) {
        if (x == month) {
            return;
        }
    }

You are trying to compare an array of integers with a single integer. So it's a bit like saying is this pen like this group of ten pens. The answer is always going to be no.

Regarding this bit:

int[] intArray = {1, 2, 3}
int[] intArray = new int{1, 2, 3, 4}
Integer[] intArray = new Integer{1, 2, 3, 4}

int is a base type that you can't call methods on, whereas Integer is a wrapper class that allows you to essentially call methods.

I'm not sure what the difference between the first two lines is, but I suspect it concerns how Java allocates memory.

James Hutchinson
  • 841
  • 2
  • 13
  • 27
0

int[] is an array of primitvs. Where Integer[] is an array of Integer objects. Thus it size is different. It is not the same type at all.

0

Or try this. With a while-loop and a boolean expression you don't have to iterate thru the whole array.

boolean match = false;
int index = 0;
while(!match && index < thirtyOneDays.length) {
    if(thirtyOneDays[index] == month) {
        match = true;

        //do what u want with the matching int
    }
index++;
}
eyebleach
  • 338
  • 3
  • 6