how access a empty array in java

Steven Désilets :

i new to Java, i want to know if its possible to access a array of size 0?I in a Java course and there a problem to solve where we need to calculate the sum of all element in a array,and if this sum is bigger than 100, we return true. We also need to calculate only positive number, no negative,and finally the code must work even if the array is empty. That my code here:

public static boolean biggerOrLower(){

    int data[] =new int[0];
    //data = new int[] {0,0,0,0,44,44,66,66,33,444,555,453,};
    int iterator = 0;
    boolean exced = false;
    int sum = 0;

   while(iterator < data.length)
    {
        if(iterator > 0) {
            sum = sum + data[iterator];
            if (sum > 100) {
                exced = true;
                break;
            }
        }
        else
        {
            exced = false;

        }
        System.out.println(sum);
        iterator++;
    }
    System.out.println(exced);
    return exced;
}

}

The problem is, since iterator is = 0 , and the length of data is also 0, it never enter the while loop, but it need too, and if i change the code to while (iterator <= data.length) i got a Exception Index 0 out of bounds for length 0.

Can somebody tell why that happen and how i ca fix that?

Thank

irfan43 :

im also a bit new to java but i think this will work

public static boolean biggerOrLower(){

    int data[] =new int[0];
    //data = new int[] {0,0,0,0,44,44,66,66,33,444,555,453,};
    boolean exced = false;
    int sum = 0;
    for(int i: data){
         if(i > 0){ sum += i}
    }
    exced = sum > 100;
    System.out.println(sum);
    System.out.println(exced);
    return exced;
}

i don't think you need to enter the loop and i believe a for loop is much better at solving this problem

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=400628&siteId=1