I am trying to read a file of multiple data types into an ArrayList object using Scanner with delimiter “\s\s”, however it doesn’t seem to work as intended. I am using printf to view if data would be stored correctly, data which I will use for calculations later on. The data seem to display correctly however I am still getting an “Incorrect File Format” exception. Also there seems to be a problem with loop. I always get stuck when using ArrayList of objects.
Sample text file:
item item descr 100 1.50
item2 item descr 250 2.50
item2 item descr 250 3.50
Code:
import java.io.*;
import java.util.*;
public class ReadItems
{
private Scanner input;
ArrayList<Item> item = new ArrayList<Item>();
//open text file
public void openFile()
{
try
{
FileReader in = new FileReader("Items.txt");
input = new Scanner(in).useDelimiter("\\s\\s");
}
catch( FileNotFoundException fileNotFound)
{
System.err.println( "Error opening file.");
System.exit(1);
}
}
//read file
public void readFile()
{
try
{
while ( input.hasNextLine())
{
item.add( new Item(input.next(), input.next(), input.nextInt(), input.nextFloat() ));
for (Item list : item)
{
System.out.printf("%-10s%-48s$%5.2f\n", list.getCode(), (list.getDecription()+ ", "+ list.getWeight()+ "g"), + list.getPrice());
//System.out.println(item);
}
}
}
catch ( NoSuchElementException elementEx)
{
System.err.println( "Incorrect file format.");
System.exit(1);
}
catch ( IllegalStateException stateEx )
{
System.err.println( "Error reading from file.");
System.exit(1);
}
}
public void closeFile()
{
if (input != null)
input.close();
}
}
Output:
item item descr, 100g $ 1.50
item item descr, 100g $ 1.50
item2 item descr, 250g $ 2.50
item item descr, 100g $ 1.50
item2 item descr, 250g $ 2.50
item2 item descr, 250g $ 3.50
Incorrect file format.
Sorry it seems i was doing a dumb thing. I wasn’t running the program through my test class where main is.
Test Class:
public class TestReadItems
{
public static void main(String[] args)
{
ReadItems application = new ReadItems();
application.openFile();
application.readFile();
application.closeFile();
}
}
The program runs without errors however i can’t seem to get the while loop to work properly. Output is tripled.
This is because your
forloop to print the output is inside thewhileloop. So, it reads each line of the file and returns the output. So, to correct, replace the outputforloop from within thewhilestatement and write it instead after thewhileloop completes.