1

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.

2 Answers 2

1

This is because your for loop to print the output is inside the while loop. So, it reads each line of the file and returns the output. So, to correct, replace the output for loop from within the while statement and write it instead after the while loop completes.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, i look at this SSCCE and i'm thinking to myself did i write this or did i ask this question? Its amazing how much one can learn in a few months :)
0

The loop can also blow up with junk at the end of the file. I added a call to .nextLine() after the item.add() call, it works fine for me now.

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());
    }
    input.nextLine(); // added
}

10 Comments

doesn't \\s implements all whitespace characters (spaces, tabs, newlines)? Therefore i believe \n wouldn't make a difference. Also i'm using input.hasNextLine(). I did try it, same results. Any comments on the while loop?
I was a little slow on my comment. How is this working for you? Why would it? hmmm
I tried changing the delimiter to \\s\\s|\n already as that was my first thought, however made no difference.
The change I suggested works for me but not for you which suggests some difference in whitespace not show in the sample data. could you attach your Sample.txt, or upload it somewhere we can see it?
For simplicity i'm usning only one line in my testing
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.