0

If I have a list like

[0,0,5,7,9]

I want to get the index position of the number "5", which is 2, and have it stop printing after that.

I've tried doing this, but it will print out 2,3, and 4. Is there a way to have it stop printing after it finds the number "5"?

    LinkedList<Integer> list = new LinkedList<Integer>();

    list.add(0);
    list.add(0);
    list.add(5);
    list.add(7);
    list.add(9);


    for(int i = 0; i< list.size(); i++){
        if(list.get(i) != 0){
            System.out.println(i);
        }
    }
jmj
  • 237,923
  • 42
  • 401
  • 438
user3718441
  • 85
  • 1
  • 3
  • 11

3 Answers3

2

Just break the for loop:

for(int i = 0; i< list.size(); i++){
    if(list.get(i) != 0){
        System.out.println(i);
        break;
    }
}
M A
  • 71,713
  • 13
  • 134
  • 174
  • OP wants to break when it finds `5` not for first non zero find – jmj Jun 25 '14 at 21:39
  • The question title is how to "retrieve the index of the first occurrence of a number of a nonzero number". In this case it happens to be 5. – M A Jun 25 '14 at 21:42
  • nevermind, there is a little conflict _Is there a way to have it stop printing after it finds the number "5"?_ – jmj Jun 25 '14 at 21:44
1

following keyword will break the execution of loop

break;

Also See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

This could also be achieved using a while loop.. For example, some pseudocode:

int count = 0     
while (keepTesting != true && count < size of the list)
{
    check integer at index [count]
    if (integer at index [count] != 0)
        set keepTesting to false
    increment count by 1  
}

You could choose any looping mechanism essentially to solve this problem..