Home > database >  Trying to find Index value of an element in an array - Timeout error
Trying to find Index value of an element in an array - Timeout error

Time:01-19

I am trying to find the index value of an element in Java. I am using 'Jdoodle' to execute the code and I am recieving a "TImeout" error. Can you please explain where exactly I went wrong?

public class MyClass {
public static void main(String args[]) {
  int[] nums = {1,2,3,4,5,6};
  int index = 0;
  int j = 0;
  int i = 2;
  while(index < nums.length){
      if(nums[index] == i){
          index = j;
      } else {
          index  ;
      }
  }
  
  System.out.println(j);
}}

CodePudding user response:

You probably confused index = j, you want j = index;

Your code should be

int[] nums = {1,2,3,4,5,6};
int index = 0;
int j = 0;
int i = 2;
while(index < nums.length){
    if(nums[index] == i){
        j = index;
        break;
    }
    index  ;
}
System.out.println(j);

The break exits the loop as soon as a result is found. This means the first valid result is printed, not the last.

  •  Tags:  
  • Related