terminate the for loop as soon as the while loop is broken

Hi, my method below is to return the number stored in the array starting from the largest index of the array, but sometimes the array may store values of 0, which i don't want to return, so how can i return the number in the array as soon as the while loop hits the array which does not contain a 0?

public int getDegree(){

int degree;

for (int i=COeff.length-1; i>=0; i--){

while (COeff != 0 && i>=0) {

degree = COeff;

}

}

return degree;

}

[541 byte] By [d-_-ba] at [2007-10-2 20:57:49]
# 1

Is there a need to use while loop for this. Is this the logic u r expecting

public class WhileReturn {

public static int getDegree(){

int COeff[] = new int[]{1, 2, 4, 0};

for (int i=COeff.length-1; i>=0; i--){

if (COeff[i] != 0) {

return COeff[i];

}

}

return 1;

}

public static void main(String[] args) {

System.out.println("Val : " + getDegree());

}

}

Cheers.

astelaveestaa at 2007-7-13 23:42:32 > top of Java-index,Java Essentials,New To Java...
# 2
> Hi, my method below is to return the number stored in> the array starting from the largest index of theWhat do you mean by "Return the number starting from" .... A method can only return one value
pat2kina at 2007-7-13 23:42:32 > top of Java-index,Java Essentials,New To Java...
# 3
u can try thisint[] ary = new int[]{1,2,0,4,5}; for(int j = ary.length-1;j>=0;j--){ if(ary[j]==0) j--; System.out.println(ary[j]); }
Kaeilvi_Pathila at 2007-7-13 23:42:32 > top of Java-index,Java Essentials,New To Java...
# 4
I think first answer covers the challenge :), but may be it's bettr to throw exception rather than return 1 if all values are 0. otherewise we can't be sure if 1 is real degree or just a special case.
s-e-r-g-ea at 2007-7-13 23:42:32 > top of Java-index,Java Essentials,New To Java...
# 5

> I think first answer covers the challenge :), but may

> be it's bettr to throw exception rather than return 1

> if all values are 0. otherewise we can't be sure if 1

> is real degree or just a special case.

Thanks for spending time to go thru that code

Astelaveesta.

astelaveestaa at 2007-7-13 23:42:32 > top of Java-index,Java Essentials,New To Java...
# 6

Yes you are right, there really was no need for the while loop, anyway, during that time i found that i really needed, some to terminate my for loop as soon as it satisfied my IF statement conditions.

I just needed a

break;

statement

But thanks for all your help, much appreciated knowing that in such a short period of time, so many people have attended my problem :D

d-_-ba at 2007-7-13 23:42:32 > top of Java-index,Java Essentials,New To Java...