Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to find Index value of an element in an array – Timeout error

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);
}}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading