Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: Reading data from a file and setting it to an array

  1. #1
    Junior Member
    Join Date
    May 2014
    Posts
    16
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Reading data from a file and setting it to an array

    Hey guys. I can read the data to a monitor perfectly. But, I'm having problem reading data from an external file into an array of class objects.

    Here's my attempt at writing the method:

    private void openFile()
        //This method asks the user to enter a file name(including the file extension) and then 
        //Sets the data to an array of Product type 
        {
        	String fileName, storeName="", emptyLine1="", emptyLine2="", name="", productName="";
    	int demandRate=0;
    	double setupCost=0.0, unitCost=0.0, inventoryCost=0, sellingPrice=0;
        	Scanner inputStream = null;
     
        	System.out.println("Please enter the file name: ");
        	fileName = console.next(); 
     
        	try
        	{
        		inputStream = new Scanner(new File(fileName));
        	}
        	catch(FileNotFoundException e)
        	{
        		System.out.println("The file does not exist.");
        		continueOptionMain();
        	}
     
        	while (inputStream.hasNextLine())
        	{
        		storeName = inputStream.nextLine(); //!!!!
        		emptyLine1 = inputStream.nextLine(); //!!!!
        		name = inputStream.nextLine();
        		productName = name.substring(7);
        		demandRate = inputStream.nextInt();
        		setupCost = inputStream.nextDouble();
        		unitCost = inputStream.nextDouble();
        		inventoryCost = inputStream.nextDouble();
        		sellingPrice = inputStream.nextDouble();
        		emptyLine2 = inputStream.nextLine();  //!!!!
        		if (storeName.equalsIgnoreCase("lambton"))
            	{
            		lambtonStore.addData("lambton", productName, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
            	}
        		else if(storeName.equalsIgnoreCase("callaghan"))
            	{
            		callaghanStore.addData("callaghan", productName, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
            	}
        	}
     
        	inputStream.close();
        	continueOptionMain();
        }

    I have put //!!!! next to the lines I believe to be the problem. The reason I think that storeName is a problem is because it is not included between every product. And I'm not entirely sure whether the empty lines are causing a problem or not.

    Here is what the example file I have is set out like:

    Lambton:

    Name: chocolate
    demand rate: 50
    setup cost: 200
    unit cost: 5.2
    inventory cost: 2
    selling price: 3

    Name: cake
    demand rate: 50
    setup cost: 300
    unit cost: 4
    inventory cost: 2
    selling price: 3.1

    Callaghan:

    Name: coffee
    demand rate: 100
    setup cost: 200.5
    unit cost: 4
    inventory cost: 2.1
    selling price: 2

    Any advice on what I'm doing wrong would be greatly appreciated


  2. #2
    Member
    Join Date
    Sep 2013
    Posts
    68
    My Mood
    Confused
    Thanks
    3
    Thanked 7 Times in 7 Posts

    Default Re: Reading data from a file and setting it to an array

    Paste the full error message that you get and your code has compilation errors like
    fileName = console.next();

    console is instance of which class? is an instance of Scanner.

  3. #3
    Junior Member
    Join Date
    May 2014
    Posts
    16
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Reading data from a file and setting it to an array

    Quote Originally Posted by aprabhat View Post
    Paste the full error message that you get and your code has compilation errors like
    fileName = console.next();

    console is instance of which class? is an instance of Scanner.
    Yes console is an instance of Scanner, sorry I didn't make that clear. It's declared at the start of the Interface class as it is used quite frequently in a number of different methods.
    Scanner console = new Scanner(System.in)

    When the debugger reaches the line
    while (inputStream.hasNextLine())
    These are the errors I get:

    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at MatesInterface.openFile(MatesInterface.java:364)
    at MatesInterface.chooseMainOption(MatesInterface.jav a:56)
    at MatesInterface.run(MatesInterface.java:14)
    at MatesInterface.chooseStoreOption(MatesInterface.ja va:135)
    at MatesInterface.continueOptionStore(MatesInterface. java:193)
    at MatesInterface.writeOutput(MatesInterface.java:291 )
    at MatesInterface.chooseStoreOption(MatesInterface.ja va:127)
    at MatesInterface.chooseMainOption(MatesInterface.jav a:48)
    at MatesInterface.run(MatesInterface.java:14)
    at MatesInterface.main(MatesInterface.java:20)

  4. #4
    Member
    Join Date
    Sep 2013
    Posts
    68
    My Mood
    Confused
    Thanks
    3
    Thanked 7 Times in 7 Posts

    Default Re: Reading data from a file and setting it to an array

    Is this your input file
    Lambton:

    Name: chocolate
    demand rate: 50
    setup cost: 200
    unit cost: 5.2
    inventory cost: 2
    selling price: 3

    Name: cake
    demand rate: 50
    setup cost: 300
    unit cost: 4
    inventory cost: 2
    selling price: 3.1

    Callaghan:

    Name: coffee
    demand rate: 100
    setup cost: 200.5
    unit cost: 4
    inventory cost: 2.1
    selling price: 2
    is yes then the problem with your code is
    [code=java]
    demandRate = inputStream.nextInt();
    [code]
    you try to read a line which is "demand rate: 50" using nextInt() method. and if this is not the file you are using then please paste the file you are trying to read.

  5. #5
    Junior Member
    Join Date
    May 2014
    Posts
    16
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Reading data from a file and setting it to an array

    Yeah that's the input file I'm trying to read to make sure it works. What would you suggest instead of nextInt()?

    Something like:

    stringDemand = inputStream.next();
    stringRate = inputStream.next();
    demandRate = inputStream.nextInt();

    EDIT: This seems to work. The code I have now is :

    private void openFile()
        //This method asks the user to enter a file name(including the file extension) and then 
        //Sets the data to an array of Product type 
        {
        	String fileName, storeName="", emptyLine1="", emptyLine2="", name="", productName="";
    		int demandRate=0;
    		double setupCost=0.0, unitCost=0.0, inventoryCost=0, sellingPrice=0;
        	Scanner inputStream = null;
     
        	System.out.println("Please enter the file name: ");
        	fileName = console.next(); 
     
        	try
        	{
        		inputStream = new Scanner(new File(fileName));
        	}
        	catch(FileNotFoundException e)
        	{
        		System.out.println("The file does not exist.");
        		continueOptionMain();
        	}
     
        	while (inputStream.hasNextLine())
        	{
        		storeName = inputStream.nextLine();
        		emptyLine1 = inputStream.nextLine();
        		name = inputStream.nextLine();
        		productName = name.substring(7);
     
        		String stringDemand = inputStream.next();
        		String stringRate = inputStream.next();
        		demandRate = inputStream.nextInt();
     
        		String stringSetup = inputStream.next();
        		String stringCost1 = inputStream.next();
        		setupCost = inputStream.nextDouble();
     
        		String stringUnit = inputStream.next();
        		String stringCost2 = inputStream.next();
        		unitCost = inputStream.nextDouble();
     
        		String stringInventory = inputStream.next();
        		String stringCost3 = inputStream.next();
        		inventoryCost = inputStream.nextDouble();
     
        		String stringSelling = inputStream.next();
        		String stringPrice = inputStream.next();
        		sellingPrice = inputStream.nextDouble();
     
        		emptyLine2 = inputStream.nextLine();    	
        		if (storeName.equalsIgnoreCase("lambton"))
            	{
            		lambtonStore.addData("lambton", productName, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
            	}
        		else if(storeName.equalsIgnoreCase("callaghan"))
            	{
            		callaghanStore.addData("callaghan", productName, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
            	}
        	}


    But I'm still getting some errors:

    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at MatesInterface.openFile(MatesInterface.java:398)
    at MatesInterface.chooseMainOption(MatesInterface.jav a:56)
    at MatesInterface.run(MatesInterface.java:14)
    at MatesInterface.main(MatesInterface.java:20)

  6. #6
    Member
    Join Date
    Sep 2013
    Posts
    68
    My Mood
    Confused
    Thanks
    3
    Thanked 7 Times in 7 Posts

    Default Re: Reading data from a file and setting it to an array

    I suggest it's beneficial for you if you read about scanner class and choose the right method according to your need and file structure.
    you can take a look at scanner class and it's methods Here.
    If your file structure is like the one you specify the inputStream.next() is not going to help you because lines in your file contain spaces and next() method is read the input only till space ans also for a long file you never know whether you get an Integer or a String.So it's better if you make your file structure homogeneous.
    Last edited by aprabhat; June 6th, 2014 at 01:39 AM.

  7. #7
    Junior Member
    Join Date
    May 2014
    Posts
    16
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Reading data from a file and setting it to an array

    Ok, I have to go to work now but I'll take a look when I get home

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,446
    My Mood
    Mellow
    Thanks
    144
    Thanked 607 Times in 594 Posts

    Default Re: Reading data from a file and setting it to an array

    What does the data in the file look like? Can you give us a short sample of the file?

  9. #9
    Junior Member
    Join Date
    May 2014
    Posts
    16
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Reading data from a file and setting it to an array

    Quote Originally Posted by GregBrannon View Post
    What does the data in the file look like? Can you give us a short sample of the file?
    I provided one at the bottom of the first post. But here it is again:

    Lambton:

    Name: chocolate
    demand rate: 50
    setup cost: 200
    unit cost: 5.2
    inventory cost: 2
    selling price: 3

    Name: cake
    demand rate: 50
    setup cost: 300
    unit cost: 4
    inventory cost: 2
    selling price: 3.1

    Callaghan:

    Name: coffee
    demand rate: 100
    setup cost: 200.5
    unit cost: 4
    inventory cost: 2.1
    selling price: 2

    Hope that helps

    --- Update ---

    Quote Originally Posted by aprabhat View Post
    I suggest it's beneficial for you if you read about scanner class and choose the right method according to your need and file structure.
    you can take a look at scanner class and it's methods Here.
    If your file structure is like the one you specify the inputStream.next() is not going to help you because lines in your file contain spaces and next() method is read the input only till space ans also for a long file you never know whether you get an Integer or a String.So it's better if you make your file structure homogeneous.
    I took your advice. I believe I need to use delimiters so that I'm only parsing in the correct values. But I'm getting a little confused and seem to be having a bit of trouble. For instance, if I declare
    inputStream.useDelimiter(: *);
    that means that inputStream won't read colons and whitespace, correct? Or am I way off?

  10. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,446
    My Mood
    Mellow
    Thanks
    144
    Thanked 607 Times in 594 Posts

    Default Re: Reading data from a file and setting it to an array

    Oh, I thought that was the desired output. It's unusual, unnecessary, and complicating to include the titles of the data fields in the file. However, since the field names add some consistency, I would read each line of the file into a 2-element String array using the split() method:
    // input is a Scanner object
    inputString[] = input.nextLine().split( ":" );
    then capture the desired data field, parsed as needed from the second element:
    name = inputString[1].trim();
    demandRate = Integer.parseInt( inputString[1].trim() );
    etc. . .

  11. #11
    Junior Member
    Join Date
    May 2014
    Posts
    16
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Reading data from a file and setting it to an array

    Quote Originally Posted by GregBrannon View Post
    Oh, I thought that was the desired output. It's unusual, unnecessary, and complicating to include the titles of the data fields in the file. However, since the field names add some consistency, I would read each line of the file into a 2-element String array using the split() method:
    // input is a Scanner object
    inputString[] = input.nextLine().split( ":" );
    then capture the desired data field, parsed as needed from the second element:
    name = inputString[1].trim();
    demandRate = Integer.parseInt( inputString[1].trim() );
    etc. . .
    It wouldn't be a uni assignment if it weren't unusual, unnecessary and complicating haha. So I tried what you suggested but I've obviously done something wrong. Here's what I got:

     
    private void openFile()
        //This method asks the user to enter a file name(including the file extension) and then 
        //Sets the data to an array of Product type 
        {
        	String fileName, storeName="", name=""; 
        	int demandRate=0;
        	double setupCost=0, unitCost=0, inventoryCost=0, sellingPrice=0;
     
        	String stringStoreName[]= new String[2];
        	String stringProductName[] = new String [2];
    		String stringDemandRate[] = new String[2];
    		String stringSetupCost[] = new String[2];
    		String stringUnitCost[] = new String[2];
    		String stringInventoryCost[] = new String[2];
    		String stringSellingPrice[] = new String[2];	
     
        	Scanner inputStream = null;
     
        	System.out.println("Please enter the file name: ");
        	fileName = console.next(); 
     
        	try
        	{
        		inputStream = new Scanner(new File(fileName));
        	}
        	catch(FileNotFoundException e)
        	{
        		System.out.println("The file does not exist.");
        		continueOptionMain();
        	}
     
        	while (inputStream.hasNextLine())
        	{    		
        		stringStoreName[] = inputStream.nextLine().split(":");//!!!!
        		storeName = stringStoreName[0].trim();
     
        		stringProductName[] = inputStream.nextLine().split(":");//!!!!
        		name = stringProductName[1].trim();
     
        		stringDemandRate[] = inputStream.nextLine().split(":");//!!!!
        		demandRate = Integer.parseInt(stringDemandRate[1].trim());
     
        		stringSetupCost[] = inputStream.nextLine().split(":");//!!!!
        		setupCost = Double.parseDouble(stringSetupCost[1].trim());
     
        		stringUnitCost[] = inputStream.nextLine().split(":");//!!!!
        		unitCost = Double.parseDouble(stringUnitCost[1].trim());
     
        		stringInventoryCost[] = inputStream.nextLine().split(":");//!!!!
        		inventoryCost = Double.parseDouble(stringInventoryCost[1].trim());
     
        		stringSellingPrice[] = inputStream.nextLine().split(":");//!!!!	
        		sellingPrice = Double.parseDouble(stringSellingPrice[1].trim());
     
        		System.out.println(name + demandRate + setupCost + unitCost + inventoryCost + sellingPrice);
     
        		if (storeName.equalsIgnoreCase("lambton"))
            	{
            		lambtonStore.addData("lambton", name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
            	}
        		else if(storeName.equalsIgnoreCase("callaghan"))
            	{
            		callaghanStore.addData("callaghan", name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
            	}
        	}
     
        	inputStream.close();
        	continueOptionMain();
        }

    With this code though I get error warning in eclipse next to a few lines (marked //!!!!). These errors are: stringStoreName etc cannot be resolved to a type, Syntax error on token "]" VariableDeclaratorID expected after this token and Duplicate local variable $missing$.

    Any advice on what I've done wrong?

  12. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,446
    My Mood
    Mellow
    Thanks
    144
    Thanked 607 Times in 594 Posts

    Default Re: Reading data from a file and setting it to an array

    With your uni instruction and my minimal explanation, you've made it more complicated than it needs to be. To simplify: read each block of data from the file in a loop; each line of each block of data is read and assigned to the same 2-element String[] array; the desired element of the String[] array is captured and stored.

    The structure is similar to my pseudo code below using the specific techniques I showed in my first post:

    // pseudo code
    String[] dataHolder = new String[2];
    while ( thereIsMoreData )
    {
        read a line of data (Name:)
     
        assign the data read to dataHolder
     
        capture the desired data from the 2nd element of dataHolder
     
        read a line of data (demand rate:)
     
        assign the data read to dataHolder
     
        capture the desired data from the 2nd element of dataHolder
     
        read a line of data (setup cost:)
     
        assign the data read to dataHolder
     
        capture the desired data from the 2nd element of dataHolder
     
        continue reading, assigning, and capturing until the whole
            data block is read
     
        create a Product object:
            product = new Product( name, demandRate, setupCost, . . ., etc. );
     
        add the new product to the desired collection
     
        repeat:  go get the data from the next block of the file (if another block exists)
    }

  13. The Following User Says Thank You to GregBrannon For This Useful Post:

    MrPigeon (June 9th, 2014)

  14. #13
    Junior Member
    Join Date
    May 2014
    Posts
    16
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Reading data from a file and setting it to an array

    Ah ok I understand now I have one slight problem though, how would I handle the store names (Lambton and Callaghan)?

    I need them to know which array to set the data to but it won't always be in the same spot. In the example file, Lambton has two products so "Lambton:" won't be repeated after the data for chocolate.

  15. #14
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,446
    My Mood
    Mellow
    Thanks
    144
    Thanked 607 Times in 594 Posts

    Default Re: Reading data from a file and setting it to an array

    So the store name is a single item in a two-element array. The second element will be either undefined, a space, or . . . ? depending on the actual items in the file. You can use that difference in the structure of the string array to programmatically do what needs to be done to handle the data.

    I wrote a short demo of a type you can/should use yourself to explore what's going on:
    // a short study in string arrays and split()
    public class TestClass2
    {
        public static void main(String[]args)
        {
            String testString[] = new String[2];
     
            testString = "this: that".split( ":" );
     
            System.out.println( "0 = " + testString[0] );
            System.out.println( "1 = " + testString[1] );
     
            // notice what a huge difference is made by simply
            // adding/removing the space after the ':'
            testString = "this: ".split( ":" );
     
            System.out.println( "0 = " + testString[0] );
            System.out.println( "1 = " + testString[1] );
     
        } // end method main()
     
    } // end TestClass2
    I pointed out in the code a very small change that makes a huge difference in the results, but what this little study demonstrates is that the difference in the data file can be used to read and interpret the data correctly.

    You will likely have to perform similar 'difference handling' for the lines that are blank.

  16. The Following User Says Thank You to GregBrannon For This Useful Post:

    MrPigeon (June 9th, 2014)

  17. #15
    Junior Member
    Join Date
    May 2014
    Posts
    16
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Reading data from a file and setting it to an array

    Sorry the delayed response, I've been pretty busy with work and studying for exams.

    Ah ok, I think I understand. I'll give it a go and let you know the results

Similar Threads

  1. reading data from pdf file
    By rammane@gmail.com in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 5th, 2014, 06:39 AM
  2. Reading data from a file into parallel arrays
    By m49er704 in forum What's Wrong With My Code?
    Replies: 12
    Last Post: April 14th, 2013, 08:58 PM
  3. Reading File and Outputting Data
    By ChrisMessersmith in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: November 13th, 2011, 12:40 PM
  4. Storing data from a file in array and setting it to textbox
    By macko in forum What's Wrong With My Code?
    Replies: 4
    Last Post: May 13th, 2011, 09:17 PM
  5. Reading data from a text file into an object
    By surfbumb in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 6th, 2011, 08:37 PM

Tags for this Thread