View Single Post
  #9 (permalink)  
Old 11-29-2007, 02:29 PM
revathi17 revathi17 is offline
Member
 
Join Date: Aug 2007
Posts: 22
revathi17 is on a distinguished road
There is actually a way to get the index..Arrays has a method
binarySearch(array to be searched,key) which returns the position of the specified key..
Using it in your program:

Code:
import java.util.*; public class LargestNo{ public static void main (String [] arg) { Scanner scan = new Scanner (System.in); int [] numbers = new int [3]; int x; int largestNumber; //int pos=0;//position in the array int index=0; System.out.print("Put in (three) numbers"); for (x=0; x<numbers.length; x++) { numbers[x]=scan.nextInt (); } largestNumber = 0; for (x=0; x<numbers.length; x++) { if (x == 0) { largestNumber = numbers[0]; //pos = 0; } if (numbers[x] > largestNumber) { largestNumber = numbers[x]; //pos = x;//x is the position of the number in the array. index = Arrays.binarySearch(numbers, largestNumber); } } System.out.println("The largest number is " + largestNumber); System.out.println("Position of the largest number:"+index); } }
I am not sure though if this would be a correct way to get the index of an array element...


Thanks,
R
Reply With Quote