I have the following program working. It takes an array of numbers and returns the index value of each number. However, what I want it to do is to get an integer from input from a user and return the index value of just that integer. If the integer is not in the array I want it to return -1.

I know I can get the user to enter input by using :

x = stdin.nextInt();

Scanner stdin = new Scanner (System.in);

int x = stdin.nextInt();

I don't know how to incorporate it to work in the following code:

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

class Arrays {
   public static void main (String [] args){
	
	  int A []= {56, 418, 93, 11, 444};
	  
	  }
	  
	  
static int find (int [] A, int N){

    for (int index = 0; index <A.length; index++){
         return index;
}
return -1;
}
}

I suggest you go read up on programming basics. You know how to retrieve an element from an array?

int x = myArray[index];

To make sure the index value is within bounds of the array, make sure the index is between 0 and array.length-1, inclusive.

It's simple, try this and please remember to indent your codes so that it makes your program much more readable and it's a good habit...(",)

Oh, don't forget the comments...

import java.lang.Math;


class Arrays {
public static void main (String [] args) {
int A[]= {56, 418, 93, 11, 444};
int Result;


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


Result =  find(x);


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


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


return -1;
} // Ends the For-Loop.
} // Ends the "find" method.
} // Ends the "Main" method.
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.