-1

If I entered 98 means it will show the position 6.

public class OddEven {
    public static void main(String args[]) {
        int[] numbers = new int[] { 14, 23, 67, 10, 76, 5, 98, 13, 110 };
        for (int i = 0; i < numbers.length; i++) {
            if(numbers[i]==14)
                System.out.println(numbers[i]+"position 0");
            else 
                System.out.println(numbers[i]+"no. not in the list");
        }
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
karthik k
  • 1
  • 1

2 Answers2

0

First, it is good to have something like this as a separate function for testability etc purposes. This also makes the code clearer. Secondly, if you are looping through, you probably don't want to do the system.out.println inside the loop

So you want something like:

public class IndexLookup {
    int[] numbers = new int[] { 14, 23, 67, 10, 76, 5, 98, 13, 110 };
    public int indexOf(int query) {
        for (int I = 0; I < numbers.length; i++) {
            if (numbers[I] == query){
                return I;
            }
        }
        return -1
    }
    public static void main(String[] args) {
        if (indexOf(98) == -1) {
            System.out.println("Not in list");
        } else {
            System.out.printf("Found %d at position %d%n", 98, indexOf(98));
        }
}
Chris Travers
  • 25,424
  • 6
  • 65
  • 182
0

Just use the code as below it will print the expected results, if you don't want array to consider the 0 position you can always increment i value to i+1 in out put statement inside the 'if' condition present in 'for' loop :-)

            boolean found = false;
            int[] numbers = { 14, 23, 67, 10, 76, 5, 98, 13, 110 };
            Scanner sc=new Scanner(System.in);  

            System.out.println("Enter the number to search");  
            int num =sc.nextInt();  
            for (int i = 0; i < numbers.length; i++) {
                if(numbers[i]==num){
                    System.out.println(numbers[i]+" position "+i);
                    found =true;
                    break;
                }
            }
            if(!found){
                System.out.println("Unable to find the Entered Number in the array");
            }
Deepak S
  • 9
  • 6