I am trying to get this program to return the index value of the number that is input by the user. It is currently returning whatever number the user inputs.

import java.lang.Math;
import java.util.Scanner;

class Arrays {
public static void main (String [] args) { 
int A[]= {3, 1, 4, 5, 9, 2, 6, 8, 7, 0};
int Result;

System.out.print("Please enter a number from 1 to 9");


Scanner stdin = new Scanner (System.in);
int x = stdin.nextInt(); 

Result = x;

if(Result == -1)
   System.out.println("\nThe number entered is not found in the array:\n"); 

else
   System.out.println("\n The index of the array element entered is: " 
   + Result);
} 

static int find (int A[], int N) {
    for(int index = 0; index < A.length; index++) 
      if(A [index] == N )
      return index;

return -1;
} 
}

Recommended Answers

All 2 Replies

Member Avatar for iamthwee
import java.lang.Math;
import java.util.Scanner;


class Arrays {
    
public static void main (String [] args) { 
int A[]= {3, 1, 4, 5, 9, 2, 6, 8, 7, 0};
int Result;

System.out.print("Please enter a number from 1 to 9");


Scanner stdin = new Scanner (System.in);
int x = stdin.nextInt(); 

Result = x;

if(find(A,Result)!=-1)
{
  System.out.println("Was found in this position");
  System.out.print(find(A,Result));
  
}
else
    System.out.println("Number not in array");
 
} 

static int find (int A[], int N) {
    for(int index = 0; index < A.length; index++) 
      if(A [index] == N )
      {
        return index; 
      }

    return -1;
} 
}

Thank you. I see where my code was wrong

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.