Reading data from a file into an array

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 12425 Views - Last Post: 09 May 2012 - 06:56 AM Rate Topic: -----

#1 roxystar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 08-May 12

Reading data from a file into an array

Posted 08 May 2012 - 08:15 AM

hi there... new here to posting - not new here to lurking/reading/getting informed/etc.

ANYWHO.

I have a java project that requires me to read from a data file and processing the data into an array... I finally got that to work, and it reads all the data from the file...

The part I am having serious issues with is taking the data from that file, and creating methods to "analyze" that data. We are given a concert.dat file that includes information such as: the name of the concert (string), the seating level (int), how many tickets (int), and the total ticket price per ticket (double). Now what I need to do with that, is put the data together (since some have repeat concerts within the file) and then create methods to get the average ticket price for each concert alike, gross sales, minimum ticket prices, max ticket prices, etc.

I honestly don't know where to go from here... any advice would be so much appreciated... thanks.

Here's the code I have thus far of reading the data into an array:

 public void readFile() throws Exception
	{
try
    	{
Scanner inFile = new Scanner(new File("concert1.dat"));
while (inFile.hasNext())
    	        {
for (int i = 0; i < concertSales.length; i++)
                 {
                	 for (int j = 0; j < concertSales[i].length; j++);
                	 {
concert[i] = inFile.next();
                 		ticketType[i] = Integer.parseInt(inFile.next());
                 		numTix[i] = Integer.parseInt(inFile.next());
                 		seatPrices[i] = Double.parseDouble(inFile.next());
  }
System.out.println(concert[i] + " " + ticketType[i] + " " + 
              							numTix[i] + " " + seatPrices[i] );
                i++;
 }
    	        }
    		 inFile.close();
}
catch (FileNotFoundException exception)
				{
					System.out.println("File not found");
				}
		    	catch (ArrayIndexOutOfBoundsException AIOOBexception)
		    	{
		    		System.out.println("Array Index is out of bounds");
		    	}		
				catch (IllegalArgumentException IAexception)
				{
					System.out.println("Divide by zero error");
				}
			} 


Is This A Good Question/Topic? 0
  • +

Replies To: Reading data from a file into an array

#2 pbl  Icon User is offline

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

Reputation: 8346
  • View blog
  • Posts: 31,905
  • Joined: 06-March 08

Re: Reading data from a file into an array

Posted 08 May 2012 - 08:23 AM

A lot of loop for nothing and when you execute your for() you don't check if the file still has data into it. And yoiu change a loop index "i" within the loop and Scanner can read int and double
 public void readFile() throws Exception
 {
    try
    {
       Scanner inFile = new Scanner(new File("concert1.dat"));
       int i = 0;
       while (inFile.hasNextLine()) {
              ticketType[i] = inFile.nextInt();
              numTix[i] = inFile.nextInt();
              seatPrices[i] = inFile.nextDouble();

              System.out.println(concert[i] + " " + ticketType[i] + " " + 
              				numTix[i] + " " + seatPrices[i] );
        ++i;
    }


Was This Post Helpful? 1
  • +
  • -

#3 roxystar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 08-May 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 08:36 AM

Ok, so I removed the for loops, but now it prints out one of my exceptions (the divide by zero error). What in the fresh hell? It also doesn't read all the data from the file anymore.

PS - sorry my previous code looked like ass.

public void readFile() throws Exception
	{
		try
    	{
			
			Scanner inFile = new Scanner(new File("concert1.dat"));
			int i = 0;
    		 while (inFile.hasNextLine())
    	        {
    			
                 		concert[i] = inFile.next();
                 		ticketType[i] = Integer.parseInt(inFile.next());
                 		numTix[i] = Integer.parseInt(inFile.next());
                 		seatPrices[i] = Double.parseDouble(inFile.next());
                		
                System.out.println(concert[i] + " " + ticketType[i] + " " + numTix[i] + " " + seatPrices[i] );
                i++;
    	        } 
    		 inFile.close();  
    	}
    
		//insert catch statements
				catch (FileNotFoundException exception)
				{
					System.out.println("File not found");
				}
		    	catch (ArrayIndexOutOfBoundsException AIOOBexception)
		    	{
		    		System.out.println("Array Index is out of bounds");
		    	}		
				catch (IllegalArgumentException IAexception)
				{
					System.out.println("Divide by zero error");
				}
			}

Was This Post Helpful? 0
  • +
  • -

#4 guntario  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 24
  • Joined: 28-March 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 08:40 AM

Is your file guaranteed to always have correctly formatted data? Your code right now will only read in properly formatted code.

One way to put all your data together would be to create a Concert class that stores the four concert related values. Instead of storing the data in separate arrays as you did above, you can store the Concert objects in an Concert[] array. You can then loop through the Concert[] array easily.
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

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

Reputation: 8346
  • View blog
  • Posts: 31,905
  • Joined: 06-March 08

Re: Reading data from a file into an array

Posted 08 May 2012 - 08:45 AM

You divide nowhere. I can you deive by zero ?
Replace
               catch (IllegalArgumentException IAexception)
                {
                    System.out.println("Divide by zero error");
                }


by
               catch (IllegalArgumentException IAexception)
                {
                    System.out.println(IAexception);
                    Thead.dumpStack();
                }


Was This Post Helpful? 0
  • +
  • -

#6 roxystar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 08-May 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 08:50 AM

View Postguntario, on 08 May 2012 - 08:40 AM, said:

Is your file guaranteed to always have correctly formatted data? Your code right now will only read in properly formatted code.

One way to put all your data together would be to create a Concert class that stores the four concert related values. Instead of storing the data in separate arrays as you did above, you can store the Concert objects in an Concert[] array. You can then loop through the Concert[] array easily.


Yes for all intents and purposes here... we are supposed to read the data from the file and put that data into a single array, which I realize now I'm not doing... Create a readFile method that is part of the main driver file, sending the contents of the file in a single array. Rats.

So, instead you mean do something like:

String[] Concert = {concert, ticketType, numTix, seatPrices}?

View Postpbl, on 08 May 2012 - 08:45 AM, said:

You divide nowhere. I can you deive by zero ?
Replace
               catch (IllegalArgumentException IAexception)
                {
                    System.out.println("Divide by zero error");
                }


by
               catch (IllegalArgumentException IAexception)
                {
                    System.out.println(IAexception);
                    Thead.dumpStack();
                }



I know I don't divide anything (yet) but later on in the program, I will be - dividing the price by numTix to get average price, etc... so I was putting my exception in. Perhaps I don't need that. I went ahead and changed what you suggested - thank you.

Now when I run it, it just prints out the first four lines of the concert1.dat file and gives me this error:

java.lang.NumberFormatException: For input string: "0,"
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Unknown Source)
at help.readFile(help.java:69)
at help2.main(help2.java:13)
Was This Post Helpful? 0
  • +
  • -

#7 guntario  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 24
  • Joined: 28-March 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 09:08 AM

Quote

So, instead you mean do something like:

String[] Concert = {concert, ticketType, numTix, seatPrices}?


No, I mean you can create a separate Concert class. IE:


public class Concert {
	
	String name;
	int row;
	int tickets;
	double price;
	
	//Add getters and setters
}


Was This Post Helpful? 0
  • +
  • -

#8 roxystar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 08-May 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 09:10 AM

View Postguntario, on 08 May 2012 - 09:08 AM, said:

Quote

So, instead you mean do something like:

String[] Concert = {concert, ticketType, numTix, seatPrices}?


No, I mean you can create a separate Concert class. IE:


public class Concert {
	
	String name;
	int row;
	int tickets;
	double price;
	
	//Add getters and setters
}



Ah okay. I can definitely do that...

If I do that though, I need to learn how to re-create my readFile method to pass the data into the Concert class? or vice versa?
Was This Post Helpful? 0
  • +
  • -

#9 guntario  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 24
  • Joined: 28-March 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 09:19 AM

Quote

If I do that though, I need to learn how to re-create my readFile method to pass the data into the Concert class? or vice versa?


Yes, instead of inserting into the arrays, just use a setter for the concert object. Then, store the concert object in the concert[] array. You can probably use an ArrayList to store the concert objects for now, because it's easy to use, and will expand automatically.
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

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

Reputation: 8346
  • View blog
  • Posts: 31,905
  • Joined: 06-March 08

Re: Reading data from a file into an array

Posted 08 May 2012 - 09:25 AM

on't know your line number anymore since your last changes but oviously

java.lang.NumberFormatException: For input string: "0,"
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Unknown Source)
at help.readFile(help.java:69)

at line 69 to try to read "0," with an invalid type (probably nextInt())

Anyhow nothing to do with division by zero :)
Was This Post Helpful? 0
  • +
  • -

#11 roxystar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 08-May 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 09:25 AM

I wish I knew how to use ArrayLists. From what I've read they do seem a lot easier to use, but it's nothing that's been covered. >.<
I'll play around with it and see where this gets me...

I also noticed I should have put the "readFile" method into the driver class, not my "account class" which I believe is what you mean by having a separate concert class (just different names).

So, I'm going to put the readFile method into the driver class (called AccountSystem) in this specific case, and then will need to read the data from the driver class back into the Account class to do the calculations.

Any suggestions on how to send the data from the driver class to my Account class? I'm going to go browse now...
Was This Post Helpful? 0
  • +
  • -

#12 roxystar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 08-May 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 11:19 AM

Ok, so now I can't even get my program to do anything...

Can someone please help me how to send data from a driver class over to just a regular class (where the setters and getters are performed?).
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

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

Reputation: 8346
  • View blog
  • Posts: 31,905
  • Joined: 06-March 08

Re: Reading data from a file into an array

Posted 08 May 2012 - 12:01 PM

View Postroxystar, on 08 May 2012 - 12:25 PM, said:

I wish I knew how to use ArrayLists.

http://www.dreaminco...post__p__391238

View Postroxystar, on 08 May 2012 - 02:19 PM, said:

Ok, so now I can't even get my program to do anything...

Can someone please help me how to send data from a driver class over to just a regular class (where the setters and getters are performed?).

class Tester {

    ArrayList<MyClass> al = new ArrayList<MyClass>();

    while(there is data to read} {
      read data
      parse it
      MyClass mc = new MyClass(field1, field2, field3);
      ac.add(mc);
    }


Was This Post Helpful? 0
  • +
  • -

#14 roxystar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 08-May 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 12:33 PM

ok, here's what i have so far. i feel like the guy from that gif that is coding away on his keyboard until his hands eventually bleed LOL.

this is my account class - called help for now lol

public class help 
{

	double concertSales[][] = new double [8][4];
	double seatPrices[] = new double [8];
	int ticketType[] = new int [8];
	int numTix[] = new int [8];
	String eventName;
	String concert[] = new String[10];
	int i, j = 0;
	int lineCount = 0;
	double seatCost;
		
	public help() 
	{
		eventName = "";
		int tix = 0, numTickets = 0;
		double seats = 0;
		this.concert[i] = eventName;
		this.ticketType[i] = tix;
		this.numTix[i] = numTickets;
		this.seatPrices[i] = seats;
	}
	
	public void setTotalTicketsSold(int tickets)
	{
		numTix[i] = tickets;
	}
	public int getTotalTicketsSold()
	{
		return numTix[i];
	}
	public void setAverageTicketPrice(int tickets, double cost)
	{
		this.numTix[i] = tickets;
		this.seatPrices[i] = cost;
	}
	public double getAverageTicketPrice()
	{
		return seatPrices[i]/numTix[i];
	}
	
	public void setGrossSales(int tickets, double seats)
	{
		this.numTix[i] = tickets;
		this.seatPrices[i] = seats;
	}
	public double getGrossSales()
	{
		return numTix[i] * seatPrices[i];
	}
	
	public double sales(String concert, int ticketType, int numTickets, double seats)
	{
		double sales = seats * numTickets;
		return sales;
	}
	public double EventConcertSales(int concert)
	{
		double totalSales = 0;
		int i = 0;
		totalSales += ticketType[i] * concertSales[concert][0];
		totalSales += ticketType[i] * concertSales[concert][1];
		totalSales += ticketType[i] * concertSales[concert][2];
		totalSales += ticketType[i] * concertSales[concert][3];
		return totalSales;
	}
	public String toString()
	{
		return ("hello" + getGrossSales() + getAverageTicketPrice());
	}
}



and here's my "main" driver class: i'm pretty sure I'm f'ed because I cannot even get it to do anything... SMH

public class help2 
{

	public void readFile() throws Exception
	{
		help event = new help();
		try
    	{
			System.out.println("fuck");
			Scanner inFile = new Scanner(new File("concert1.dat"));
			int i = 0;
    		while (inFile.hasNextLine())
    	        {
                 		event.concert[i] = inFile.next();
                 		event.ticketType[i] = inFile.nextInt();
                 		event.numTix[i] = inFile.nextInt();
                 		event.seatPrices[i] = inFile.nextDouble();
                		
                //System.out.println(event.concert[i] + " " + event.ticketType[i] + " " + event.numTix[i] + " " + event.seatPrices[i] );
                ++i;
    	        } 
    		 inFile.close();  
    	}

				catch (FileNotFoundException exception)
				{
					System.out.println("File not found");
				}
		    	catch (ArrayIndexOutOfBoundsException AIOOBexception)
		    	{
		    		System.out.println("Array Index is out of bounds");
		    	}		
				catch (IllegalArgumentException IAexception)
				{
					System.out.println(IAexception);
					Thread.dumpStack();
				}
			}
	public static void main(String[] args)
	{
		/*int i, j = 0;
		help event = new help();
		event.getTotalTicketsSold();
		event.getAverageTicketPrice();*/
	}
}


Was This Post Helpful? 0
  • +
  • -

#15 guntario  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 24
  • Joined: 28-March 12

Re: Reading data from a file into an array

Posted 08 May 2012 - 01:36 PM

This may sound strange to you, but believe me, this helps:

Before trying to code this out, sit down and think out the whole data flow process. Just sitting down and drawing out exactly what should happen will help tremendously with coding your program. The hard part of coding is figuring out how to make something work, not the actual coding part.

Try making an array in the help2 class that will store all your help objects, and move the

help event = new help();


to inside your while loop. Also add each object to the array within the loop.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2