How to reverse an ArrayList from a file? - java

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!

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);

Related

Reading a text file into Java by using a "double" method

I have a simple text file with the following content:
4 5 2 7
I would like Java to read this file and create an array with it. However, I want my method that I use to keep its "double" properties. I'm having a hard time getting my array command to figure it out though:
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;
public class ReadFile {
public static void main(String[] args){
gns(Arr);
}
public static double gns(String TxtFile) throws IOException {
Path path = Paths.get("C:\\Users\\me\\files\\inputfiles");
int numLines = (int)Files.lines(path).count();
Scanner fileScanner = new Scanner(new FileReader("TxtFile.txt"));
double Arr = new ArrayList<String>();
return Arr;
}
}
It keeps giving me an array due to the type of the array.
This would do the trick :
double[] arr = Files.lines(Paths.get(PATH))
.flatMap(line -> Arrays.stream(line.split(" ")))
.mapToDouble(Double::parseDouble)
.toArray();
Here we read the file line by line and then split it using " ", parse each number and covert it to an array of double. You can then return arr[] from your method gns(String TxtFile).
Scanner#nextDouble
Give a try to the following one, full example below:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NextDouble {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input.txt"));
List<Double> doubles = new ArrayList<Double>();
while (sc.hasNextDouble()) {
doubles.add(sc.nextDouble());
}
System.out.println(doubles); // => [1.0, 3.0, 8.0, 6.0, 5.0]
}
}
input.txt contains the following line:
1 3 8 6 5
You can find more about scanner in the doc
You're trying to set Arr which is of type double to an ArrayList of type String, this is not possible since the types double and ArrayList are different.
If you wanted an arraylist of doubles use
ArrayList<Double> d = new ArrayList<>();

Java - Read in text file, compute employee hours from most to least

This is for my beginning Java class. There are similar questions asking to sort the values that are given in an array; I know how to do that, but here I need to read in a text file, and then sort the values and display them by employee name and the hours that they worked, while also keeping the order from most to least. This is what the text file looks like:
Jim 4 5 6 1 2 3 4
Harry 6 5 1 3 9 2 0
John 2 3 1 6 7 8 4
Lisa 2 1 5 4 1 2 6
And here is all that I know about reading in text files and my current code for this project.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class EmployeeWorkHours {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File file = new File("/Users/ODonnell/Desktop/inputData.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Parsing
Look at the Javadoc for java.util.Scanner, or use autocomplete in your IDE, you'll see a lot more methods than nextLine() etc, the ones of interest
hasNextInt() returns true when next token is a number
nextInt() the next integer
Storage
Now you need to store your numbers, I'd recommend a List as you won't know how many there are upfront which rules out primitive arrays.
Create a list with List hours = new ArrayList();
Add to it with add()
You'll also need to store your employees names, for simplicity I'd recommend using a Map of String to hours list, i.e. Map>.
Create with Map> employeeHours = new HashMap>()
Add to using employeeHours.put(name, hours)
Sorting
java.util.Collections.sort is all you need. This will sort your list by default in ascending order.
Displaying
Most if not all built in list implementations by default implement toString() so you can simply call System.out.println(hours)
You should save the hours worked and the names of your employees in a HashMap.
http://en.wikipedia.org/wiki/Hash_table For an explation of a HashMap.
After storing your values you can sort the HashMap like it is explained in the following link:
Sort a Map<Key, Value> by values (Java)
You should use next() method on scanner instance to read next token instead of whole line. Then you have to try to parse it to integer to recognize if it is a name of employee or its work hour. In the for loop we are sorting data (using Collections utility class) and printing it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class EmployeeWorkHours {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File file = new File("inputData.txt");
Map<String, List<Integer>> data = new HashMap<String, List<Integer>>();
try {
Scanner scanner = new Scanner(file);
List<Integer> currentEmployee = null;
while (scanner.hasNextLine()) {
String token = scanner.next();
try {
currentEmployee.add(new Integer(token));
} catch (NumberFormatException e) {
currentEmployee = new ArrayList<Integer>();
data.put(token, currentEmployee);
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (String name : data.keySet()) {
Collections.sort(data.get(name));
Collections.reverse(data.get(name));
System.out.println(name + " " + data.get(name));
}
}
}

How to add elements from string added from console to a list in java

How I can add elements to a list from a input in java.
Like if i put:
Scanner reader = new Scanner("a,b,c,d,e);
I want to Have it like String[] a = {a,b,c,d,e];
Using any Scanner Methods with whiles , Really i am little bit lost
Sorry for my English( is not my main language)
If you know how many input items you are going to accept, declare an array before you start the input, then put each input into the array until you run out of array space.
The better way to do this is to use ArrayList:
ArrayList<String> inputList = new ArrayList<String>();
Using a Scanner, you can retrieve the next input (if you want an entire line, use reader.nextLine() to get that string. I'd suggest storing that in a local variable temporarily so you can examine it if you need to (you'll need some sort of termination sentinel or use hasNextLine() to see if there is more to read.
If you then need to return as an array, ArrayList has a toArray() method you can call.
To add inputs to list like this
import java.util.ArrayList;
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
ArrayList<String> inputList = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
inputList.add(input);
while (!input.equals("null")) {
input = reader.nextLine();
inputList.add(input);
}
}
}
This should work, the default token used by Scanner is whitespace characters.
public String[] getStringArray(String input, int arraySize) {
String[] stringArray = new String[arraySize];
Scanner s = new Scanner(input);
for (int i = 0; s.hasNext(); i++) {
stringArray[i] = s.next();
}
s.close();
return stringArray;
}

Reading ints from a txt file and storing to an array

I am trying to read integers from a text file and store them into an array. The text file reads:
4
-9
-5
4
8
25
10
0
-1
4
3
-2
-1
10
8
5
8
Yet when I run my code I get [I#41616dd6 in the console window...
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("Integers.txt");
int[] integers = new int [100];
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
integers[i] = input.nextInt();
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(integers);
}
You're printing out the virtual memory address of the array instead of the actual array items:
You can print out the actual array items, one by one, like this:
// This construct is called a for-each loop
for(int item: integers) {
System.out.println(item);
}
#akuhn points out correctly that Java has a built in helper for this:
System.out.println(Arrays.toString(integers));
Note that you'll need to add:
import java.util.Arrays
in your imports for this to work.
Unfortunately, Java’s designers missed to add a proper string representations for arrays.
Instead use
System.out.println(Arrays.toString(integers));
You need to import java.util.Arrays; to make this work.
instead of this
System.out.println(integers);
try this
System.out.println(integers[0] + " : " + integers[1]);
you need to print actual values in integers[] array not array itself
If using an int array is not a restriction, then i would suggest use List. You can use it like this :
List<Integer> integers = new ArrayList<Integer>();
Scanner input = new Scanner(file);
while(input.hasNext()){
integers.add(scanner.nextInt());
}
System.out.println(integers);
Output : [1,2,-1,23]
Whenever you pass any object to System.out.println(), it prints the toString() for that object. If its not overridden, it prints the memory address of that object.
System.out.println(integers);
is trying to print toString() representation of integer array which is nothing but the JVM address of this array.
To print the actual numbers in the array, you either need to iterate through the array or convert the array to java.util.ArrayList.(which has the toString() method implemented.)
This should help you to read Integer from a file and store it in array
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class filetoarray {
public static ArrayList<Integer> read(File f)
{
ArrayList<Integer> array=new ArrayList<Integer>();
try
{
Scanner sc=new Scanner(f);
while(sc.hasNextLine())
{
array.add(sc.nextLine());
}
}
catch(Exception e)
{
System.out.printf("ERROR : %s", e);
}
return array;
}
public static void main(String[] args) {
File file1=new File("file1.txt");//your file path here
ArrayList<Integer> array1;
array1=read(file1);
System.out.println(array1);
}
}

How do I create an iterator that will return only the elements that are different in Java?

More details of the issue:I need to create an iterator for a Stack of Strings that uses an ArrayList that returns only the words that are different after making the words all lowercase in the file and uses the Scanner for this. I must sort the array in the end. I have to create two separate classes for this problem.
This is what I have so far:
import java.io.*;
import java.util.*;
public class StackClass
{
static StringSet stringStack;
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
stringStack = new StringSet();
System.out.println("Please input the filename: ");
String fileName = console.next();
try {
FileReader file = new FileReader(fileName);
Scanner input = new Scanner(file);
while (input.hasNext())
{
input.useDelimiter("\\W");
//lcString.toLowerCase();
(I commented this out^ until I figure it out)
stringStack.add(input.next());
}
}
catch (FileNotFoundException e) {e.printStackTrace();}
}
}
And here is my other class:
import java.util.*;
public class StringSet implements Iterable<String>
{
static Stack<String> stringStack;
private ArrayList<String> stackList = new ArrayList<String>();
//for loop goes through all the words in stack
//if the word is found then ignore it, if not add it to the stack
public String add(String s)
{
for(int i=0;i>0;i++)
{
stringStack.push(s);
}
return s;
}
public int size( int i)
{
return stringStack.size();
}
public Iterator<String> iterator()
{return new WordIterator();}
class WordIterator implements Iterator<String>
{
private int i=0;
public boolean hasNext(){return i>0;}
public String next(){return stackList<String>;}
}
}
If the problem is "how to iterate only through unique words", I would simply use a HashSet for the words, and as you push words onto the stack
1) If the word is in the HashSet, don't push it on.
2) If the word is not in the HashSet, push it on and add it to the HashSet.
If you need to keep track of the number of occurrences, you can use a HashMap instead of a HashSet, where you increase the number of duplicate strings you encounter.
If you need to preserve the ordering & number of occurrences for something, I would keep a separate non-unique Stack where I'd just push everything.
I hope I understood your problem correctly.

Categories

Resources