I've already gotten this program to run and it almost gives me the answer I want. After running the whole program, it's supposed to print out the index of the key and what the key is equal too. I cannot for the life of me figure out how to get the index into the final message in the console. For example, if you have an array of {0,1,2,3,4,5,6,7,8,9} and your key is 0, it's supposed to return: list[0] = 0. I labeled the part I think where my problem lies with "(index???)"
import java.util.Scanner;
public class PartA {
public static void main(String[] args){
System.out.println("Please enter 10 double values:");
double [] array = inputArray();
selectionSort(array);
printArray(array);
System.out.println("Please enter a search key:");
Scanner input = new Scanner(System.in);
double key = input.nextDouble();
double x = binarySearch(array,key);
if (x != -1)
System.out.println("list[" + (index???) + "] = " + key);
else
System.out.println(key + " is not on the list");
}
public static double[] inputArray(){
Scanner array = new Scanner(System.in);
double [] list = new double[10];
for(int i = 0; i < list.length; i++){
array.hasNextDouble();
list[i] = array.nextDouble();
}
return list;
}
public static void selectionSort(double[] list){
double array[] = new double [list.length];
for(int i = 0; i < list.length; i++){
for(int j = 0; j < list.length; j++){
if (list[i] < list[j]){
double x = list[i];
list[i] = list[j];
list[j] = x;
}
}
}
}
public static void printArray(double[] list){
for (int i = 0; i < list.length; i++){
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.println();
}
public static int binarySearch(double []list, double key){
int low = 0, high = list.length - 1;
while(high >= low){
int mid = (low + high)/2;
if(key < list[mid])
high = mid - 1;
else if(key == list[mid])
return mid;
else low = mid + 1;
}
return -1;
}
}
x, right? So what do you conclude? Why isxdeclared as double, since it's supposed to represent an index in an array? Why do you call itxrather than...index?