-1

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.

  1. I need to fill the values of an array (double[] myArray) using
    Scanner input from a single line for multiple doubles.
  2. 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

Pshemo
  • 113,402
  • 22
  • 170
  • 242
  • 1
    And what is wrong with your code? Does it not compile/throws exception/returns wrong results? – Pshemo Oct 18 '14 at 15:51
  • 2
    i dont see a description of your problem/error – Dima Oct 18 '14 at 15:52
  • 1
    Hint: What will happen to the first element and the last element when you reverse the array? What can you say about the second element and the second-from-last element? Good Luck! – Solomon Slow Oct 18 '14 at 16:00
  • Scanner sc2 = new Scanner(System.in); int j = 0; while (sc2.hasNext()) { //Another Failed Attempt to collect the input from a single line if (sc2.hasNextDouble()) { myArray[j] = sc2.nextDouble(); //Insert user input into array j++; } } Collections.reverse(Arrays.asList(myArray));//Doesn't work :( – Clark Elliott Oct 18 '14 at 16:07
  • Sorry, I tried to add a 2nd scanner, my problem is that When the imput 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. – Clark Elliott Oct 18 '14 at 16:08
  • This question appears to be off-topic because the author constantly changing his question – Dima Oct 18 '14 at 17:00

7 Answers7

3

You misunderstood something here.

In Collections.reverse(Arrays.asList(myArray)); you use Arrays.asList(myArray) that is returning a new List. Afterwards you reverse it, but you don't assign it to a variable and you just lose it.

That's not how you need to do it.

You need to think of another way of doing it.

I'll give you a hint: use the hint in the question!

and if you say you just need to reverse it, why do you need to sort it?!

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Dima
  • 8,448
  • 4
  • 25
  • 56
  • Java docs for `asList` says: `Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)` – PeterMmm Oct 18 '14 at 16:24
  • I wanted to accomplish the reverse with a for loop to run through the array and print each double value starting with the end of the array and counting down i-- I believe I will receive points marked off for this however as the assignment calls for the array itself to be reversed :( – Clark Elliott Oct 18 '14 at 16:43
  • again: USE THE HINT! you need to swap 1st with last, second with pre last until you get to the middle, thats the hint! – Dima Oct 18 '14 at 16:58
1

I need to fill the values of an array (double[] myArray) using Scanner input from a single line for multiple doubles.

If I understand this correctly first you need to read entire line and then parse it to read all double values from it. To read entire line of doubles from user you can invoke nextLine from scanner which handles System.in stream. Then you can either

  • split line on spaces and use Double.parseDouble(String) (to get double from String) on each String element from result array
  • wrap this line with another Scanner and use its nextDouble.

BTW if you want to read next line after nextDouble (or nextInt or nextAnythingExceptLine) you need to consume reminded line separators with another nextLine method (more info here Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods).

So first part of your assignment can look like

Scanner sc = new Scanner(System.in);

System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); 
sc.nextLine();//consume line separator to let `nextLine` read actuall next line
double[] myArray = new double[arraySize]; 

System.out.print("Please input " + arraySize
        + " double numbers in one line: ");
String line = sc.nextLine();
System.out.println("your numbers are "+line);

Scanner lineScanner = new Scanner(line);         
int j = 0;
while (lineScanner.hasNextDouble()) {
    myArray[j++] = lineScanner.nextDouble(); 
}
lineScanner.close();

Your second problem is that generics don't support primitive types so T in asList(T..) can be only object type. Unfortunately autoboxing works only on primitive types, so double[] can't be promoted to Double[] because every array is already an object (even arrays of primitive types).
This means that result of Arrays.asList(T.. data) for argument myArray of type double[] will not return List<double> or List<Double> but List<double[]> — a list which holds one object, the passed array, not the elements of this array. That is why reversing doesn't work for you (reversing list containing one element changes nothing, as you can't reorder list with only one element).

To solve this problem simply change type of myArray form double[] (array of primitive types) to Double[] (array of object types), to let generic type T from asList(T..) represent non-primitive Double (otherwise T can only be inferred as non-primitive double[] type).

So change your line

double[] myArray = new double[arraySize]; // Create array[userInput]

to

Double[] myArray = new Double[arraySize]; // Create array[userInput]
Community
  • 1
  • 1
Pshemo
  • 113,402
  • 22
  • 170
  • 242
  • Thank you so much, I appreciate all the information about primitive and object arrays, also I got the program working perfectly now, I appreciate the help! – Clark Elliott Oct 18 '14 at 16:52
  • You are welcome :) but really next time when you ask question focus on describing not only on what you want to achieve but on how your code is not working as you expected. Simple "doesn't work" tells us nothing. Comments in code are nice but they will not replace description of problem in question itself. Anyway good luck with your study :) – Pshemo Oct 18 '14 at 16:55
0

Probably you have to instantiate a new Scanner after you have read the array size.

    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]
    sc.close();

    sc = new Scanner(System.in).useDelimiter(",");
    System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
    int j = 0;
PeterMmm
  • 22,286
  • 12
  • 68
  • 104
0
Collections.reverse(Arrays.asList(myArray));//Doesn't work :(

First of all: Arrays.asList get Object varargs and if you pass primitive array you'll get list of primitive arrays.

Second moment: Arrays.asList returns list. And if you changed it list your original array(from which you create list) will not be changed.

You shall make collection instead array and reverse it. For example:

Scanner sc = new Scanner(System.in);

System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input

System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
List<Double> myList = new ArrayList<Double>();
for (int i = 0; i < arraySize;) {
    if (sc.hasNextDouble()) {
        myList.add(sc.nextDouble());
        i++;
    }
}  

Collections.reverse(myList);//Doesn't work :(

System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++) 
    System.out.println(myList.get(i));
WidWing
  • 176
  • 1
  • 10
0

Use this to reverse your array.

You need to get half of the array's length to get the full reverse of the array

for(double i = 0; i < Array.length / 2; i++)
{
    int x = Array[i];
    Array[i] = Array[Array.length - i - 1];
    Array[Array.length - i - 1] = x;
}
Brandon Minnick
  • 11,396
  • 12
  • 55
  • 108
0
package display.pkg1;
import java.util.Scanner;

public class Display1 {

    public static void main(String[] args) {
        
         Scanner input = new Scanner(System.in);
         
   
           System.out.println(" Enter the size of array ");
        int size = input.nextInt();
         System.out.println(" Enter array Elements ");
         
         double []lol = new double [size];
         
         for(int i =0 ; i<size ; i++)
         {
         lol[i] = input.nextDouble();
         
         }

          for(int i =size-1 ; i>=0 ; i--)
         {
                       System.out.println(" Array element " + ( i +1) + " is " + lol[i]);
          
         }
    
}
}
Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
Ali Hatem
  • 1
  • 1
-1

Try this code

import java.util.Scanner;

public class ReverseArray{

    public static void main(String[] args) {

        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

        for(int i = 0; i < myArray.length; i++){
            if (sc.hasNextDouble()) {
                myArray[i] = sc.nextDouble(); //Insert user input into array
               }
        }           

        // Reverse myArray
        for(int i = 0, j =  myArray.length-1; i < (myArray.length/2); i++, j--){
            Double temp = myArray[i];
            myArray[i] = myArray[j];
            myArray[j] = temp;          
        }
        //Print the reversed myArray
        System.out.println("After reverse order: ");
        for (int i=0;i<arraySize;i++) 
            System.out.println(myArray[i]);
    }
}
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
  • 1
    While this answer is probably correct and useful, it is preferred if you include some explanation along with it to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. – Kevin Brown May 29 '15 at 22:12