Reputation: 25
This is the original question:
Write a program that reads a set of doubles from a file, stores them in an array or ArrayList, and then prints them back out to the console (using System.out.println statements) in REVERSE order.
For example, if the input file input.txt file contains
27.3 45.6 98.3 10.1
The console output will display 10.1 98.3 45.6 27.3
And this is the code I have so far:
package reverse;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class reversed {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Scanner numFile = new Scanner(new File("input.txt"));
ArrayList<Double> list = new ArrayList<Double>();
while (numFile.hasNextLine()) {
String line = numFile.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter(" ");
while(sc.hasNextDouble()) {
list.add(sc.nextDouble());
}
sc.close();
}
numFile.close();
System.out.println(list);
}
}
How would I reverse the ArrayList I created? The code I have works, I just have no idea how to reverse it. And where exactly would I put that code? Thanks!
Upvotes: 0
Views: 759
Reputation: 201467
You don't need to reverse the ArrayList
, just iterate it in reverse order. Something like,
for (int i = list.size(); i > 0; i--) {
System.out.println(list.get(i - 1));
}
If you must reverse the List
before iteration, you might use Collections.reverse(List)
like
Collections.reverse(list);
Upvotes: 3