14 Replies - 6565 Views - Last Post: 11 March 2012 - 09:23 PM Rate Topic: -----

#1 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Populate ArrayList of different data types from text file

Posted 06 March 2012 - 08:18 PM

I would like to create an ArrayList from data types stored in a text file.
The ArrayList would be multidimensional with four data types; String, String, int, float.
The text file format may vary. I simply need to store the programs data in text files.

Example text file could be:

Item-Number Description Shipping-Weight(kg) Price
MHDD1T Maxtor, 1 terabyte 3 120.00
XVTSV60 Vizio, 60 inch HDTV 40 1200.00

I would use other text file to store sales tax, shipping rate etc...

I know how to do with single data type (String) however for multiple data types i don't see how its possible. I simply would like to know if its possible and some advice as to how to go about doing it.

Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: Populate ArrayList of different data types from text file

#2 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 08:27 PM

That should be :
Item-Number   Description          Shipping-Weight(kg)  Price
MHDD1T        Maxtor, 1 terabyte     3                   120.00 
XVTSV60       Vizio, 60 inch HDTV    40                 1200.00[list]


Was This Post Helpful? 0
  • +
  • -

#3 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1148
  • View blog
  • Posts: 2,522
  • Joined: 05-May 05

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 09:00 PM

Use legacy collections.

class Test {

    static List<ArrayList> table = new ArrayList<ArrayList>();

    public static void main(String[] args) {
        ArrayList row1 = new ArrayList();
        row1.add(new String(""));
        row1.add(new Float(1f));
        table.add(row1);
    }
}



You'll have to cast carefully. Another alternative it use generic collections where you store each element as a string. Then, try to parse each element as a float or integer to tell what is what.

This post has been edited by blackcompe: 06 March 2012 - 09:02 PM

Was This Post Helpful? 1
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 09:57 PM

The real best approach is to write a class that hold all the info and use an ArrayList of that class

macosxnerd101 wrote a tutorial about that
http://www.dreaminco...arallel-arrays/
Was This Post Helpful? 2
  • +
  • -

#5 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 10:19 PM

This is how i attempted to do it

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
			{
				input = new Scanner( new File("Items.txt"));
			}
			catch( FileNotFoundException fileNotFound)
			{
				System.err.println( "Error opening file.");
				System.exit(1);
			}
		}
		
		//read file
		public void readFile()
		{
			try
			{
				while ( input.hasNext())
				{
					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());
			        }
			        
				}
					
			}
			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();		
		}
	
}






public class TestReadItems
{

public static void main(String[] args) 
    {
	ReadItems application = new ReadItems();
	application.openFile();
	application.readFile();
	application.closeFile();
	}
}


I'm getting the Incorrect file format exception. Maybe its time i use a tokenizer. Base on what you guys are saying i'm not sure if my approach is correct though.
Was This Post Helpful? 0
  • +
  • -

#6 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1148
  • View blog
  • Posts: 2,522
  • Joined: 05-May 05

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 10:25 PM

Are you trying to read the file header too? You file shouldn't have that.

Quote

Item-Number Description Shipping-Weight(kg) Price


You should get rid of the commas in your file too.

item.add( new Item(input.next(), input.next(), input.nextInt(), input.nextFloat() ));                       


There are five elements per line, yet you're parsing only 4.

Quote

MHDD1T Maxtor, 1 terabyte 3 120.00

This post has been edited by blackcompe: 06 March 2012 - 10:25 PM

Was This Post Helpful? 0
  • +
  • -

#7 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 10:34 PM

View Postpbl, on 06 March 2012 - 09:57 PM, said:

The real best approach is to write a class that hold all the info and use an ArrayList of that class

macosxnerd101 wrote a tutorial about that
http://www.dreaminco...arallel-arrays/


That's the stipulation of the assignment, data has to be stored in text files.

blackcompe, on 06 March 2012 - 10:25 PM, said:

I have file without commas for now until i establish a tokenizer.
i have like so

MHDD1T Maxtor 3 120.00
.


I have file without commas for now until i establish a tokenizer.
i have like so

MHDD1T Maxtor 3 120.00
.
.
Was This Post Helpful? 0
  • +
  • -

#8 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1148
  • View blog
  • Posts: 2,522
  • Joined: 05-May 05

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 10:40 PM

Maybe this will help:

import java.util.Scanner;

class Test {

    public static void main(String[] args) {
        String src = "one,   two,three";
        Scanner lexer = new Scanner(src);
        while (lexer.hasNextLine()) {
            String[] tokens = lexer.nextLine().split(",");
            Item i = new Item(tokens[0].trim(), tokens[1].trim(), tokens[2].trim());
            System.out.println(i);
        }

    }
}

class Item {

    String a, b, c;

    Item(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    @Override
    public String toString() {
        return "Item [a=" + a + ", b=" + b + ", c=" + c + "]";
    }

}


Was This Post Helpful? 1
  • +
  • -

#9 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 10:46 PM

The thing is i'm going to do calculations with the weight and price in the program that's why i need them to be int and float respectively. I can't escape casting can i.
Was This Post Helpful? 0
  • +
  • -

#10 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1148
  • View blog
  • Posts: 2,522
  • Joined: 05-May 05

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 10:49 PM

Use Integer.parseInt to create an integer from a string. The float equivalent is Float.parseFloat.
Was This Post Helpful? 1
  • +
  • -

#11 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 10:50 PM

View Postblackcompe, on 06 March 2012 - 10:40 PM, said:

Maybe this will help:

import java.util.Scanner;

class Test {

    public static void main(String[] args) {
        String src = "one,   two,three";
        Scanner lexer = new Scanner(src);
        while (lexer.hasNextLine()) {
            String[] tokens = lexer.nextLine().split(",");
            Item i = new Item(tokens[0].trim(), tokens[1].trim(), tokens[2].trim());
            System.out.println(i);
        }

    }
}

class Item {

    String a, b, c;

    Item(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    @Override
    public String toString() {
        return "Item [a=" + a + ", b=" + b + ", c=" + c + "]";
    }

}



I am not to familiar with this, i will look into this.

Thanks
Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Populate ArrayList of different data types from text file

Posted 06 March 2012 - 11:01 PM

class Item {  
     String a, b, c;  
     Item(String a, String b, String c) {  
        this.a = a;  


means
class Item {  
     String a <-- this is a instance variable, b, c;  
     Item(String a <-- this a parameter to the constructor, String b, String c) {  
        this.a = a;  


this.a = a; means

set to the a instance variable the value of the a parameter to the constructor
so the equivalent of
class Item {  
     String MyA, b, c;  
     Item(String a, String b, String c) {  
        MyA = a;  


Was This Post Helpful? 0
  • +
  • -

#13 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Re: Populate ArrayList of different data types from text file

Posted 07 March 2012 - 04:04 AM

View Postpbl, on 06 March 2012 - 11:01 PM, said:

class Item {  
     String a, b, c;  
     Item(String a, String b, String c) {  
        this.a = a;  


means
class Item {  
     String a <-- this is a instance variable, b, c;  
     Item(String a <-- this a parameter to the constructor, String b, String c) {  
        this.a = a;  


this.a = a; means

set to the a instance variable the value of the a parameter to the constructor
so the equivalent of
class Item {  
     String MyA, b, c;  
     Item(String a, String b, String c) {  
        MyA = a;  



When i said 'this' i meant the English word this :bigsmile:
I was really referring to the tokenizing method, thanks though.
Was This Post Helpful? 0
  • +
  • -

#14 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Re: Populate ArrayList of different data types from text file

Posted 11 March 2012 - 08:48 AM

Can someone tell me why my output is being duplicated:

Output with printf:

MHDD1T    Maxtor, 1 terabyte, 2kg                         $120.00
MHDD1T    Maxtor, 1 terabyte, 2kg                         $120.00
XVTSV60   Vizio, 60 inch HDTV, 50kg                       $1200.00
MHDD1T    Maxtor, 1 terabyte, 2kg                         $120.00
XVTSV60   Vizio, 60 inch HDTV, 50kg                       $1200.00
FX6860    Gateway, Gaming Desktop, Black, 20kg            $1100.00



Output of ArrayList:

[Item{code=MHDD1T, decription=Maxtor, 1 terabyte, weight=2, price=120.0}]
[Item{code=MHDD1T, decription=Maxtor, 1 terabyte, weight=2, price=120.0}, Item{code=XVTSV60, decription=Vizio, 60 inch HDTV, weight=50, price=1200.0}]
[Item{code=MHDD1T, decription=Maxtor, 1 terabyte, weight=2, price=120.0}, Item{code=XVTSV60, decription=Vizio, 60 inch HDTV, weight=50, price=1200.0}]
[Item{code=MHDD1T, decription=Maxtor, 1 terabyte, weight=2, price=120.0}, Item{code=XVTSV60, decription=Vizio, 60 inch HDTV, weight=50, price=1200.0}, Item{code=FX6860, decription=Gateway, Gaming Desktop, Black, weight=20, price=1100.0}]
[Item{code=MHDD1T, decription=Maxtor, 1 terabyte, weight=2, price=120.0}, Item{code=XVTSV60, decription=Vizio, 60 inch HDTV, weight=50, price=1200.0}, Item{code=FX6860, decription=Gateway, Gaming Desktop, Black, weight=20, price=1100.0}]
[Item{code=MHDD1T, decription=Maxtor, 1 terabyte, weight=2, price=120.0}, Item{code=XVTSV60, decription=Vizio, 60 inch HDTV, weight=50, price=1200.0}, Item{code=FX6860, decription=Gateway, Gaming Desktop, Black, weight=20, price=1100.0}]




Here is my edited 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()+ "kg"), + list.getPrice());
			        	//System.out.println(item);
			        }
			        input.nextLine();      
				}
					
			}
			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();		
		}
	
}





Sample text:
MHDD1T        Maxtor, 1 terabyte               2                   120.00 
XVTSV60       Vizio, 60 inch HDTV              50                 1200.00
FX6860        Gateway, Gaming Desktop, Black   20                 1100.00



Was This Post Helpful? 0
  • +
  • -

#15 xiphias  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 14-February 12

Re: Populate ArrayList of different data types from text file

Posted 11 March 2012 - 09:23 PM

Figured this out, thanks.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1