Baha Baghdadi
Baha Baghdadi

Reputation: 29

For loop not running correctly

When I execute this code the output is "140" which is "28*5" but it should be "150" which is "28+31+30+31+30" it should calculate the days between 2 months "feb" and "july"... So it means that the for loop isn't working correctly or what ? and why is that ! can you help me here ?? PS: I tried to change the j++ in the loop to j+1 but Android Studio Says"that's not a statement"

int[] pair = {1,3,5,7,8,10,12};
int[] impair = {4,6,9,11};
int x=0;
int j;
int year=2015;
int mm=2;
int month=7;
String msg="";
if (month>mm) {
    for (j = mm; j<month; j++){
        if (Arrays.asList(impair).contains(j)){
            x = 31 + x;
        }else if(Arrays.asList(pair).contains(j)){
            x = 30 + x;
        }else{
            if (year%4==0) {
                x= 29 + x;
            }else{
                x= 28 + x;
            }
        }
    }
    System.output.println(x);
}

Upvotes: 0

Views: 151

Answers (3)

Shreyas Chavan
Shreyas Chavan

Reputation: 1099

This is because your loop never enters the first two if blocks as that is not how aslist(array).contains(element) works

Java, Simplified check if int array contains int

Checking whether an element exist in an array

Upvotes: 0

gaurav gupta
gaurav gupta

Reputation: 147

This is because the asList() requires a class object which is either a collection and Iterable. You could modify your code in the following way:-

Integer[] pair = {1,3,5,7,8,10,12};
Integer[] impair = {4,6,9,11};
int x=0;
int j;
int year=2015;
int mm=2;
int month=7;
String msg="";
if (month>mm) {
    for (j = mm; j<month; j++){
        if (Arrays.asList(impair).contains(new Integer(j))){
            x = 31 + x;
        }else if(Arrays.asList(pair).contains(new Integer(j))){
            x = 30 + x;
        }else{
            if (year%4==0) {
                x= 29 + x;
            }else{
                x= 28 + x;
            }
        }
    }
    System.output.println(x);
}

This should give you the correct output.

Upvotes: 1

rgettman
rgettman

Reputation: 178333

You are attempting to convert the int[] to a List<Integer> by calling Arrays.asList. But that results in a List<int[]> of a single element (the original int[]), which doesn't contain any value of j. The reason is given in Arrays.asList() not working as it should? -- it's a generic method, and the type parameter must be a reference type. int[] is a reference type (as all arrays are), but int isn't.

That is why the tests all fail and 28 is repeatedly chosen to be added.

Change the declared types of pair and impair from int[] to Integer[], so that Arrays.asList will infer the type as Integer (a reference type) correctly. Then the contains method will work as expected. With this change I get 150.

Upvotes: 8

Related Questions