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 8 of 8

Thread: problem reading from two files into array objects

  1. #1
    Junior Member
    Join Date
    May 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Post problem reading from two files into array objects

    Hello, I am new to programming and Java in general so I apologize for my ignorance.

    I am writing a vending machine program that reads in information from two files. There are different vending machines that do different things, and there are more than one machine of the same type (there are two model 100A machines and three model 100B machines, one model 100C machine). This first file "machines.dat" looks like:

    100A 2 <-- model number, number of machines
    0 0 0 <-- initial quarters, dimes, nickels in machine
    5 <-- number of items in machine
    1A 1034 5 <-- item selector, product I.D. number, and quantity of product
    1B 1000 10
    1C 1100 10
    1D 1123 20
    1E 1210 5
    0 0 0 <-- second 100A machine begins.
    7
    1A 2180 20
    1B 1283 20
    1C 3629 5
    1D 3649 3
    1E 4051 15
    1F 4211 1
    1G 5318 5

    The file "products.dat" looks like:

    1000 20 55 chocolate chips <-- product I.D. number, quantity of item, price in cents,
    1034 10 50 candy bar and then the description.
    1100 17 75 cookies

    Here is the code I have for the constructor thus far:
    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.Scanner;
     
    public class machinelist
    {
    	Scanner inFile;
    	StringTokenizer tokenizer;
    	String item_selector, product_id, quantity, machine,  file = "machines.dat";
    	int numberOf_machines, quarters, nickels, dimes, num_items;
     
    	machinelist[] model;
     
    	public machinelist()
    	{
    		try
    		{
    			inFile = new Scanner(new File(file));
     
    			while (inFile.hasNext())
    			{
    				machine = inFile.next();
    				numberOf_machines = inFile.nextInt();
    				for(int i = 0; i<=numberOf_machines; i++)
    				{
    					quarters = inFile.nextInt();
    					dimes = inFile.nextInt();
    					nickels = inFile.nextInt();
    					num_items = inFile.nextInt();
    				}
    					for (int j = 0; j < num_items; j++)
    					{
    						item_selector = inFile.next();
    						product_id = inFile.next();
    						quantity = inFile.next();
    					}
    				}
    			}
    				catch (FileNotFoundException exception)
    			    {
    				    System.out.println ("The file " + file + " was not found.");
        			}
         			catch (IOException exception)
    				{
    				    System.out.println (exception);
        			}
     
    			}
     
    	/*		model = new machinelist[7];
     
    			machinelist[0] = new 100A1 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
     
    		    machinelist[1] = new 100A2 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
     
    			machinelist[2] = new 100B1 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
     
    			machinelist[3] = new 100B2 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
     
    			machinelist[4] = new 100B3 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
     
    			machinelist[5] = new 100C  (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
     
    			machinelist[6] = new 100D  (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
     
     
    */
     
     
    }

    The code at the top is what reads in from machines.dat

    I have the objects commented out because I think I need to put them in a switch statement, but I am not sure exactly how to do that.

    The machine models will be their own classes. I am not sure what to do with the data from products.dat or what exactly to put them.

    Any suggestions, criticism, rips, shreds, lacerates, would be much appreciated.

    Thank you.


  2. #2
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: problem reading from two files into array objects

    Code must be readable, so I recommend getting the indentation right, and adhering to the Java naming convention (class names start with an uppercase letter, variable and method names with a lowercase character) - it's confusing as it is.

    If you're catching an IOException, Best Practice suggests that you close the IO resource before leaving - put a 'finally' block after the 'catch', check the Scanner isn't null, and close it if it isn't. It may not be very important in a small, one-off application, but always clearing up resources in a 'finally' block can potentially save system resources being wasted or running low.

    Some of those class member variables (the ones that won't have their values shared between methods) can be made method variables. Best Practice suggests declaring variables as close to their point of use as is practical.

  3. #3
    Junior Member
    Join Date
    May 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem reading from two files into array objects

    Thank you dlorde for your input. As for saving system resources I am not as worried about that as making the program work Unfortunately I am uneducated in the 'finally' block; my teacher has only taught us the try and catch statements as well as types of exceptions for catching errors when dealing with inputting from a file.

    Here is an update of what I have done, I have a better idea of how to solve this problem and I have tried to increase the readability of the code

    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.Scanner;
     
    public class Machinelist
    {
    	Scanner inFile;
    	StringTokenizer tokenizer;
    	String item_selector, product_id,typeOf_machine,  file = "machines.dat", select_machine;
    	int numberOf_machines, quarters, nickels, dimes, num_items, quantity;
     
    	machine[] model = new int[numberOf_machines];
     
    	public void machinelist()
    	{
     
    		try
    		{
    			inFile = new Scanner(new File(file));
    			//read in from the file
    			while (inFile.hasNext())
    			{
    				typeOf_machine = inFile.next();           //grab first item from "machines.dat " which is the  machine type
    				numberOf_machines = inFile.nextInt();     //grab next item which is number of machines
    				for(int i = 0; i<=numberOf_machines; i++) //set up loop to read in items the machines share from "machines.dat"
    				{
    					quarters = inFile.nextInt();
    					dimes = inFile.nextInt();
    					nickels = inFile.nextInt();
    					num_items = inFile.nextInt();
     
    					for (int j = 0; j < num_items; j++) //set up loop to grab the rest of the information from "machines.dat"
    					{
    						item_selector = inFile.next();
    						product_id = inFile.next();
    						quantity = inFile.nextInt();
    					}
    					//create machine objects
    					machine[numberOf_machines] = new typeOf_machine + i (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
    				}
    			}
     
    				//handle exceptions dealing with inputting from file.
    				catch (FileNotFoundException exception)
    			    {
    				    System.out.println ("The file " + file + " was not found.");
        			}
         			catch (IOException exception)
    				{
    				    System.out.println (exception);
        			}
     
    			//set up main menu to load in
    			System.out.println("Initializing machines. Please wait...");
    			System.out.println("Machines are ready.");
    			System.out.println("Available machines: 100A1, 100A2, 100B1, 100B2, 100B3, 100C1, 100D1");
    			System.out.println("");
    			System.out.print("Please select a machine: ");
    			select_machine = scan.next();
     
    			//The way this is set up needs to be changed.
    			switch (select_machine)
    			{
    				case 100A1:
    					machine[0] = new 100A1 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
    					break;
    				case 100A1:
    					machine[1] = new 100A2 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
    					break;
    				case 100B1:
    					machine[2] = new 100B1 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
    					break;
    				case 100B2:
    					machine[3] = new 100B2 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
    					break;
    				case 100B3:
    					machine[4] = new 100B3 (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
    					break;
    				case 100C1:
    					machine[5] = new 100C  (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
    					break;
    				case 100D1:
    					machine[6] = new 100D  (quarters, nickels dimes, num_items, item_selector,
    										product_id, quantity);
    					break;
    		//		case secret:
    		//		print out report for machines.
    		//		break;
    			}
     
     
     
     
     
    }
    Last edited by JavaRTnoob; May 25th, 2010 at 05:57 PM.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: problem reading from two files into array objects

    Have you tried to compile your code yet?
    When you do, please be sure to copy and paste the error message console on the forum with your questions.


    Comments on the code:
    You shouldn't use known machine types as variable names in your code. What happens if a new type comes out? You shouldn't have to rewrite the code with every new type.
    Save the machine type in a variable, say machineType = ....

    You probably want a class/object to hold the data for each machine.
    Last edited by Norm; May 25th, 2010 at 08:22 PM.

  5. #5
    Junior Member
    Join Date
    May 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem reading from two files into array objects

    Norm, thanks for your input. I have a much better idea of what I am doing now and how to go about the solution. There will be the file Machinelist.java that will read it from 'machines.dat' and store those into objects of type Machine100A1, Machine100A2.. etc. Here is the updated code:

    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.Scanner;
     
    public class Machinelist
    {
    	Scanner inFile;
    	StringTokenizer tokenizer;
    	String item_selector, product_id,typeOf_machine,  file = "machines.dat", select_machine;
    	int numberOf_machines, quarters, nickels, dimes, num_items, quantity, index = 0;
    	String[] itemSelector = null;
    	int[] productID = null;
    	int[] quantity = null;
     
     
    	Machine[] model = new machine[10];
     
     
    	public void machinelist()
    	{
     
    		try
    		{
    			inFile = new Scanner(new File(file)).useDelimiter("\\s+");;
    			//read in from the file
    			while (inFile.hasNext())
    			{
    				typeOf_machine = inFile.next();           //grab first item which is machine
    				numberOf_machines = inFile.nextInt();     //grab next item which is number of machines
    				for(int i = 1; i<=numberOf_machines; i++) //set up loop to read in items the machines share from "machines.dat"
    				{
    					quarters = inFile.nextInt();
    					dimes = inFile.nextInt();
    					nickels = inFile.nextInt();
    					num_items = inFile.nextInt();
    					itemSelector = new String[num_items];
    					productID = new int[num_items];
    					quantity = new int[num_items];
     
     
    					for (int j = 0; j < num_items; j++) //set up loop to grab the rest of the information from "machines.dat"
    					{
    						item_selector[j] = inFile.next();
    						product_id[j] = inFile.next();
    						quantity[j] = inFile.nextInt();
    					}
     
     
    					//create machine objects
    				 if (typeOf_machine.equals("100A1"))
    						 	machine[index] = new Machine100A1(quarters, nickels, dimes, num_items, item_selector,
    										product_id, quantity);
    								//make new array to store machine names here.
    										index++;
    				 if (typeOf_machine.equals("100A2"))
    							machine[index] = new Machine100A2(quarters, nickels, dimes, num_items, item_selector,
    										product_id, quantity);
    										index++
    				 if (typeOf_machine.equals("100B1"))
    							machine[index] = new Machine100B1(quarters, nickels, dimes, num_items, item_selector,
    										product_id, quantity);
    										index++;
    				 if (typeOf_machine.equals("100B2"))
    							machine[index] = new Machine100B2(quarters, nickels, dimes, num_items, item_selector,
    										product_id, quantity);
    										index++;
    				 if (typeOf_machine.equals("100B3"))
    							machine[index] = new Machine100B(quarters, nickels, dimes, num_items, item_selector,
    										product_id, quantity);
    										index++;
    				 if (typeOf_machine.equals("100C1"))
    							machine[index] = new Machine100C1(quarters, nickels, dimes, num_items, item_selector,
    										product_id, quantity);
    										index++;
    				 if (typeOf_machine.equals("100D1"))
    							machine[index] = new Machine100D1(quarters, nickels, dimes, num_items, item_selector,
    										product_id, quantity);
    										index++;
     
     
    				}
    			}
     
    				scan.close()
     
     
    				//handle exceptions dealing with inputting from file.
    				catch (FileNotFoundException exception)
    			    {
    				    System.out.println ("The file " + file + " was not found.");
        			}
         			catch (IOException exception)
    				{
    				    System.out.println (exception);
        			}
    }
    }
    			//set up main menu to load in
    			System.out.println("Initializing machines. Please wait...");
    			System.out.println("Machines are ready.");
    			System.out.println("Available machines: " + );
    			System.out.println("");
    			System.out.print("Please select a machine: ");
    			select_machine = scan.next();
    /*
    			if(select_machine.equals("100A1")
    				//method call to machine class 100A1
    		      	if(select_machine.equals("100A2")
    				//method call to machine class 100A2
    			if(select_machine.equals("100B1")
    				//method call to machine class 100B1
    			if(select_machine.equals("100B2")
    				//method call to machine class 100B2
    			if(select_machine.equals("100B3")
    				//method call to machine class 100B3
    			if(select_machine.equals("100C1")
    				//method call to machine class 100C1
    			if(select_machine.equals("100D1")
    				//method call to machine class 100D1
    }
    }

    Norm, I cannot compile the code yet because the line: Machine[] model = new machine[10]; refers to a machine class that has not be written yet. But in that Machine class, we will read it from the file "products.dat" and store them in array objects. Hopefully using inheritance these objects will have access to all the information they need.

    My question now is, at the end of the cod there are these if statements to handle what machine the user wants to purchase items from. Can I do it this way? I had a switch statement there before but I was told that was not a good idea.

    Norm. I will comment out the code that will not compile and post some of the errors that I am getting and do not understand.

    Thanks for your help.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: problem reading from two files into array objects

    You shouldn't hard code any currently know data values in your program. You should get the machine types from a file and save in an array or collection of some type. Then use a loop to process each machine type.
    The above depends on the following:
    How do you correlate the processing to be done with each machine type? Is the processing different for each machine type? Or is it the same?
    If different then you'll need to write specific code for each type as your are doing now.
    If same, then you need to rewrite your code.

  7. #7
    Junior Member
    Join Date
    May 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: problem reading from two files into array objects

    I have renamed a bunch of stuff and wrote some classes and it does compile.

    Norm, the machines are all different. They have different inventory and distrubute change differently.

    The file looks like this:

    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.Scanner;
     
    public class Machine
    {
    	String typeOf_machine,  file = "machines.dat", select_machine;
    	int numberOf_machines, quarters, nickels, dimes, num_items, index = 0;
    	String[] itemSelector = null;
    	int[] productID = null;
    	int[] quantity = null;
     
    	AllMachine[] modelList = new AllMachine[10];
     
    	public Machine()
    	{
    		Scanner inFile;
    		try
    		{
    			inFile = new Scanner(new File(file)).useDelimiter("\\s+");;
    			//read in from the file
    			while (inFile.hasNext())
    			{
    				typeOf_machine = inFile.next();           //grab first item which is machine
    				numberOf_machines = inFile.nextInt();     //grab next item which is number of machines
    				for(int i = 1; i<=numberOf_machines; i++) //set up loop to read in items the machines share from "machines.dat"
    				{
    					quarters = inFile.nextInt();
    					dimes = inFile.nextInt();
    					nickels = inFile.nextInt();
    					num_items = inFile.nextInt();
    					itemSelector = new String[num_items];
    					productID = new int[num_items];
    					quantity = new int[num_items];
     
    					for (int j = 0; j < num_items; j++) //set up loop to grab the rest of the information from "machines.dat"
    					{
    						itemSelector[j] = inFile.next();
    						productID[j] = inFile.nextInt();
    						quantity[j] = inFile.nextInt();
    					}
    //problems here
    						//create machine objects
    					if (typeOf_machine.equals("100A1"))
    					{
    						modelList[0] = new Machine100A1(quarters, nickels, dimes, num_items, itemSelector,
    															productID, quantity);
    						index++;
    					}
    				/*	if (typeOf_machine.equals("100A2"))
    					{
    						modelList[index] = new Machine100A2(quarters, nickels, dimes, num_items, itemSelector,
    															productID, quantity);
    						index++;
    					}
    					if (typeOf_machine.equals("100B1"))
    					{
    						modelList[index] = new Machine100B1(quarters, nickels, dimes, num_items, itemSelector,
    															productID, quantity);
    						index++;
    					}
    					if (typeOf_machine.equals("100B2"))
    					{
    						modelList[index] = new Machine100B2(quarters, nickels, dimes, num_items, itemSelector,
    															productID, quantity);
    						index++;
    					}
    					if (typeOf_machine.equals("100B3"))
    					{
    						modelList[index] = new Machine100B(quarters, nickels, dimes, num_items, itemSelector,
    															productID, quantity);
    						index++;
    					}
    					if (typeOf_machine.equals("100C1"))
    					{
    						modelList[index] = new Machine100C1(quarters, nickels, dimes, num_items, itemSelector,
    															productID, quantity);
    						index++;
    					}
    					if (typeOf_machine.equals("100D1"))
    					{
    						modelList[index] = new Machine100D1(quarters, nickels, dimes, num_items, itemSelector,
    															productID, quantity);
    						index++;
    					} */
     
    				}
    			}
     
    			inFile.close();
    		}
     
    		//handle exceptions dealing with inputting from file.
    		catch (FileNotFoundException exception)
    		{
    			System.out.println ("The file " + file + " was not found.");
    		}
    		catch (IOException exception)
    		{
    			System.out.println (exception);
    		}
     
    	}
     
     
    	public void AllTransactions()
    	{
    		Scanner scan = new Scanner(System.in);
    		//set up main menu to load in
    		System.out.println("Initializing machines. Please wait...");
    		System.out.println("Machines are ready.");
    		System.out.println("Available machines: 100A1, 100A2, 100B1, 100B2, 100B3, 100C1, 100D1");
    		System.out.println();
    		System.out.print("Please select a machine: ");
    		select_machine = scan.next();
     
    		while (!select_machine.equals("EXIT"))
    		{
    			//method call to machine class 100A1
    			if(select_machine.equals("100A1"))
    				modelList[0].transactions();
     
    			//method call to machine class 100A2
    			else if(select_machine.equals("100A2"))
    				modelList[1].transactions();
     
    			//method call to machine class 100B1
    			else if(select_machine.equals("100B1"))
    				modelList[2].transactions();
     
    			//method call to machine class 100B2
    			else if(select_machine.equals("100B2"))
    				modelList[3].transactions();
     
    			//method call to machine class 100B3
    			else if(select_machine.equals("100B3"))
    				modelList[4].transactions();
     
    			//method call to machine class 100C1
    			else if(select_machine.equals("100C1"))
    				modelList[5].transactions();
     
    			//method call to machine class 100D1
    			else if(select_machine.equals("100D1"))
    				modelList[6].transactions();
     
    			//invalid model number error
    			else
    				System.out.println("Invalid Machine. Try again.");
     
    			System.out.print("Please select a machine: ");
    			select_machine = scan.next();
    		}
    	}
    }

    This file extends AllMachine class which just instantiates the parameters of the machines. Machine100A1 is a class right now just prints out some details. There is a VendingMachine class that just creates a machine object. I am complieing and getting this error message:

    Please select a machine: 100A1
    Exception in thread "main" java.lang.NullPointerException
    at Machine.AllTransactions(Machine.java:121)
    at VendingMachine.main(VendingMachine.java:8))

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: problem reading from two files into array objects

    What object reference/variable is null at line 121?
    Check that you are reading something from the file by using println()s to show what was read:
    System.out.println("typeOf_machine=" + typeOf_machine);

    index++;
    What is this supposed to do? The array indexes are fixed values for each machine. You don't compute them.


    Don't use hardcoded literals for array addressing. For example 0 for machine x, 1 for machine y etc
    If you must use an array, define some constants for each machine's index:
    final static int MACHINEx_IDX = 0;
    ditto for rest

    Then you don't have to lookup the correct index to use. It will be built from the name of the machine
    Last edited by Norm; May 30th, 2010 at 09:29 AM.

Similar Threads

  1. Reading CSV files into a program
    By Wrathgarr in forum Java Theory & Questions
    Replies: 2
    Last Post: April 15th, 2010, 10:41 AM
  2. Reading and Writing Text Files
    By kappasig84 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: March 1st, 2010, 07:16 PM
  3. Reading many files using a scanner
    By jayjames90 in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: October 22nd, 2009, 04:35 PM
  4. [SOLVED] Creation of objects of Array in Java
    By sadi_shihab in forum Collections and Generics
    Replies: 4
    Last Post: July 9th, 2009, 01:38 PM
  5. Reading IEEE float values from files.
    By username9000 in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: June 30th, 2009, 12:56 PM