Please support our Java advertiser: Lunarpages Java Web Hosting
Views: 719 | Replies: 2
![]() |
•
•
Join Date: Apr 2006
Posts: 3
Reputation:
Rep Power: 0
Solved Threads: 0
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:
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;
}
}•
•
Join Date: Mar 2006
Posts: 20
Reputation:
Rep Power: 3
Solved Threads: 0
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.
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.
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)





Linear Mode