Details of my Homework
Topic: Single Dimensional Array
Write a java program that first read in the size of a one dimensional array, read in each array element of double type, reverses the order of this one-dimensional array. Do not create another array to hold the result. Hint: Use the code in the text for exchanging two elements.
Sample Output:
Please input the size of array: 4
Please input 4 double numbers: 1.0, 2.0, 3.0, 4.0
After reverse order: 4.0, 3.0, 2.0, 1.0
I have 2 problems with my assignment. Wondering if anyone can help me find a solution.
- I need to fill the values of an array (double[] myArray) using
Scanner input from a single line for multiple doubles. - I need to reverse the order of the values inside the array WITHOUT using a 2nd array.
This is my code so far.
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
int j = 0;
while (sc.hasNext()) { //Another Failed Attempt to collect the input from a single line
if (sc.hasNextDouble()) {
myArray[j] = sc.nextDouble(); //Insert user input into array
j++;
}
}
Collections.reverse(Arrays.asList(myArray));//Doesn't work :(
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myArray[i]);
My problem is that when the input for the doubles is given by the user the console moves to the next line still expecting input, if input is given ArrayIndexOutOfBounds
is thrown