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

Thread: Loop used to read different data values from a text file

  1. #1
    Junior Member
    Join Date
    Jul 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Loop used to read different data values from a text file

    Hello everyone.
    For my lab, I need to read some values from a text file.
    So here are the data values:
     
    Focus Wagon ZTW
    18445.0
    5
    Color
    10
    Fort Knox Gold Clearcloat Metallic
    0
    Liquid Grey Clearcoat Metallic
    0
     Infra-Red Clearcoat
    0
    Grabber Green Clearcoat Metallic
    0
    Sangria Red Clearcoat Metallic
    0
    French Blue Clearcoat Metallic
    0
    Twilight Blue Clearcoat Metallic
    0
    CD Silver Clearcoat Metallic
    0
    Pitch Black Clearcoat
    0
    Cloud 9 White Clearcoat
    0
    Transmission 
    2
    Auto
    0
    Standard
    -815
    Brakes
    3
    Standard
    0
    ABS
    400
    ABS with Advance Trac
    1625
    Side Impact Air Bags
    2
    Present
    0
    Not Present 
    0
    Power Moonroof
    2
    Present
    0
    Not Present 
    0
    Each Option in the above data has a price which is directly below it.
    I'm supposed to instantiate using the data from above, serialize it, and deserialize the Automotive object. I'm getting a nullpointerexception which i post at the bottom of this post.
    Thanks! All help is appreciated
    Here is what I have so far
    Automotive Class
    package Model;
     
    import java.util.ArrayList;
     
    public class Automotive {
    	//Variables
    	private String properties;
    	private String name;
    	private float carBasePrice;
    	private int numberOfOptionSets;
     
    	public OptionSet[] optSet;
    	ArrayList OptionSetList;
    	//Overloaded Constructors
    	public Automotive(String name, float carBasePrice) {
    		super();
    		this.name = name;
    		this.carBasePrice = carBasePrice;
    		 ArrayList<OptionSet> OptionSetList = new ArrayList<OptionSet>();
    	}
    	public Automotive(String name) {
    		super();
    		this.name = name;
    		 ArrayList<OptionSet> OptionSetList = new ArrayList<OptionSet>();
     
    	}  public Automotive() {
    		 OptionSet[] optSet = new OptionSet[6];
     
    	}
     
    	public Automotive(float carBasePrice) {
    		super();
    		this.carBasePrice = carBasePrice;
    		 ArrayList<OptionSet> OptionSetList = new ArrayList<OptionSet>();
     
    	}public Automotive(String name, Float carBasePrice, int optcount) {
    		optSet = new OptionSet[optcount];
    		this.name = name;
    		this.carBasePrice = carBasePrice;
    		this.numberOfOptionSets = optcount;
    	}
    	//Getter and Setter Methods
    	public String getName() {
    		return name;
    	}
     
    	public void setName(String name) {
    		this.name = name;
    	}
     
    	public double getBaseprice() {
    		return carBasePrice;
    	}
    	public void setBaseprice(float carBasePrice) {
    		this.carBasePrice = carBasePrice;
    	}
    	//Other Class methods
    	public void updateBasePrice(float carBasePrice){ 
    		this.carBasePrice = carBasePrice;
    	}
    	public void addOptionSet(OptionSet b) {
    		OptionSetList.add(b);
    	}public void addOptionSet(int a) { //problem
    		optSet[a] = new OptionSet(a);
     
    	}public void addOptionSet(int index, int size, String name) {
    		optSet[index] = new OptionSet(name, size);
    	}public void setOption(int indexOfOptionSet, int indexOfOption, String name, float price) {
    		optSet[indexOfOptionSet].setOption(indexOfOption, name, price);
    	}
    	public int findOptionSet(String name) {
    		return (optSet.toString().indexOf("name"));
    	}public void updateOptionSet(int i, int newPrice,  String newName) {
    		optSet[i] = new OptionSet(newName, newPrice);
    	} public void deleteOption(int l) {
    		try {
    			optSet[l] = null;
    		} catch (NullPointerException e) {		//ignored
    		}
    	}
    	 public void print() {
    	        System.out.println(name);
    	        System.out.println(carBasePrice);
    	        System.out.println(numberOfOptionSets);
    	        for (OptionSet optionset : optSet) {
    	            optionset.printOptSet();
    	        }
    	    }
    	}
     
    	//Add print method and a tostring method that is nicely formatted.

    OptionSet

     
    package Model;
     
    import java.util.ArrayList;
     
    public class OptionSet {
    	private String name;
    	 Option[] OptSet;
    	private Option Options;
    	private int numberOfOption;
    	public OptionSet(String name, int count) //Add constructors with name and opt input. default constructor
    	{
    		this.name = name;
    		OptSet = new Option[count];
    		this.numberOfOption = count;
    	}
    	public OptionSet(String name) {
    		this.name = name;
     
    	} 
    	public OptionSet(int count) {
    		Option[] OptSet = new Option[count];
    		for (Option opt: OptSet) {
    			 opt = new Option();
    		}
    	};
    	//Setters and Getters
    	public String getName() {
    		return name;
    	}
     
    	public void setName(String name) {
    		this.name = name;
    	}
    	public Option getOption(int i) {
    		return OptSet[i];
    	}public Option getOption(String name) {
    		return findOption(name);
    	} public double getOptionPrice(String name) {
    		return findOption(name).getBaseprice();
    	}
     
    	public void setOption (int i, String name, double price) {
    		OptSet[i].setBaseprice(price);
    		OptSet[i].setName(name);
     
    	//Setters and Getters End
     
    	}public Option findOption(String name) {
    		return OptSet[OptSet.toString().indexOf("name")];
    	} public void updateOption(int i,String newName) {
    		OptSet[i].setName(newName);
    	} public void updateOption(int i, int newPrice) {
    		OptSet[i].setBaseprice(newPrice);
    	} public void deleteOption(int l) {
    		try {
    			OptSet[l] = null;
    		} catch (NullPointerException e) {		//ignored
    		}
    	} public void printOptSet() {
    		for (Option Opt : OptSet) {
    			System.out.println((Opt.toString()));
    		}
    	}
    	public class Option { //Make the Option class an inner class of OptionSet (for Lab 1)
    		//Variables
    		private String name;
    		private double baseprice;
    		//Constructors
    		public Option() { }
     
    		public Option(String name, double baseprice) {
    			super();
    			this.name = name;
    			this.baseprice = baseprice;
    		}
     
    		public Option(String name) {
    			super();
    			this.name = name;
    		}
     
    		public Option(double baseprice) {
    			super();
    			this.baseprice = baseprice;
    		}
    		//Getters and Setters
    		public String getName() {
    			return name;
    		}
    		public void setName(String name) {
    			this.name = name;
    		}
    		public double getBaseprice() {
    			return baseprice;
    		}
    		public void setBaseprice(double baseprice) {
    			this.baseprice = baseprice;
    		}
    		public void printOption() {
    			StringBuffer output = new StringBuffer("Name:");
    			output.append(name);
    			output.append(", Price $");
    			output.append(baseprice);
    			System.out.println(output.toString());
    		}
     
    	}
    }
    FILE IO class
    package Util;
     
    import java.io.*;
    import java.util.Scanner;
    import java.util.StringTokenizer;
     
    import Model.*;
     
    public class Fileio {
     
    	public static Automotive readDataFile() {
    		Automotive a1 = null;
     
    		try {
    		String input = null;
    		BufferedReader bf = new BufferedReader(new FileReader("data.txt"));
    		Scanner sc = new Scanner(bf);
    		StringTokenizer tok, eni;
    		boolean procceed = false;
    		while (procceed == true) {
    				if (sc.hasNext()) {
    					input = sc.nextLine();
    				}
    				float cost = 0;
    				if(sc.hasNext()) {
    					cost = sc.nextFloat();
    				}
    				int numOptionSets = 0;
    				if(sc.hasNext()) {
    					numOptionSets = sc.nextInt();
    				}
    		  a1 = new Automotive(input, cost, numOptionSets);
     
    		  for (int k = 0; k < numOptionSets; k++) {
    			  if(sc.hasNext()) {
    				  input = sc.nextLine();
    				  tok = new StringTokenizer(input, ":");
    				  String optSetName = tok.nextToken();
                      int optSetSize = Integer.parseInt(tok.nextToken());
                      a1.addOptionSet(k, optSetSize, optSetName);
    			  }
     
    			  for (int l = 0; l < k; l++) {
    				  if (sc.hasNext()) {
    					  eni =  new StringTokenizer(input, ":");
    					  String token2 = eni.nextToken();
    					  float d = Float.parseFloat(eni.nextToken());
     
    					  a1.setOption(k, l, token2, d);
                  }
              }
    		    procceed = false;
    		} 
    		}
    		sc.close();
    	} catch (Exception e) {
     
    	}
    	return a1;
    	}
     
    	public static void serialize(Automotive car)
    	{
            try {
    			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("auto.ser"));
    			out.writeObject(car);
    			out.close();
            } catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
     
    	public static Automotive deserialize(String file) 
    	{
    		Automotive test = null;
    		 try {
    	            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    	            test = (Automotive) in.readObject();
    	        } catch (IOException excep) {
    	           excep.printStackTrace();
    	        } catch (ClassNotFoundException g) {
    	           System.out.println("Error" + g.toString());
    	        }
    	        return test;
     
    	     }
     
     
     
    	}
    Driver Class:
    package Model;
     
    import Util.Fileio;
     
    public class Driver {
     
        public static void main(String[] args) {
            //Build Automobile Object from a file.
            Automotive FordZWT = Fileio.readDataFile();
            //Print attributes before serialization
            FordZWT.print();
            //Serialize the object
            Fileio.serialize(FordZWT);
            //Deserialize the object and read it into memory
            Automotive newFordZTW = Fileio.deserialize("auto.ser");
            //Print new attributes
            newFordZTW.print();
        }
    }

    I have this exception:
    Exception in thread "main" java.lang.NullPointerException
    	at test.readDataFile(test.java:59)
    	at test.main(test.java:92)
    Last edited by mjrox96; July 10th, 2013 at 02:18 PM. Reason: added more of my code


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Loop used to read different data values from a text file

    It's interesting your code is looking for "Ford" when there is no "Ford" in the data you've posted.

    What you've described and kind of posted sounds like the data should be of the form:

    Item
    Cost
    Item
    Cost
    Etc. . . .

    Data in that consistent form would be easy enough to read with a sc.nextLine(), returning a String, parsing to numbers as needed.

    Your data suggests that a Transmission - any transmission - adds to the cost of the vehicle. That's odd.

    Your code isn't far from a reasonable approach. Have you tried it? Are you getting errors? If so, post them and describe what you need help with. Otherwise, I'm not sure what your questions are.

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

    mjrox96 (July 9th, 2013)

  4. #3
    Junior Member
    Join Date
    Jul 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Loop used to read different data values from a text file

    Could you just use the next() function instead of nextLine()?

  5. #4
    Junior Member
    Join Date
    Jul 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Loop used to read strings, numbers, etc and assign them from data values from a text file

    .

  6. #5
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: Loop used to read strings, numbers, etc and assign them from data values from a text file

    Please provide an SSCCE. I have no idea what goes wrong.

  7. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Loop used to read different data values from a text file

    It looks like you've started another thread on this topic, but I'll answer your last question:

    You can use the next() method (not "function" in Java) with increased difficulty or complexity. You should consider the lines of data with multiple 'tokens' and determine the different results that will be obtained when using nextLine() or next(). For example, what will each of those Scanner methods return when applied to the following line of data?

    Fort Knox Gold Clearcloat Metallic

  8. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Loop used to read strings, numbers, etc and assign them from data values from a text file

    Please don't start duplicate topics in multiple sub-forums.
    Return to
    ***threads merged***

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

    jps (July 10th, 2013)

  10. #8
    Junior Member
    Join Date
    Jul 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Loop used to read different data values from a text file

    Here is the exception:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at Model.OptionSet.findOption(OptionSet.java:43)
    at Model.OptionSet.getOption(OptionSet.java:33)
    at Util.test.main(test.java:59)

  11. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Loop used to read different data values from a text file

    The error you've posted is complaining about an array index being out of bounds (-1), but there are no arrays visible in the code you've posted. Can you possibly post the code related to the error? If you're not sure how to find the relevant code, post the entire OptionSet class.

  12. #10
    Junior Member
    Join Date
    Jul 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Loop used to read different data values from a text file

    i posted all the code for my lab and the exception. I appreciate the help!

  13. #11
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Loop used to read different data values from a text file

    How will the posted code ever get past the first while() in class Fileio:

    boolean procceed = false;
    while (procceed == true) {

    I don't know how the code you posted gets past that to the error you posted. Did you post the latest version of your code? Even when I fix the above a build a text file from which to read the data needed, I get stopped by other errors.

    Something doesn't add up.

Similar Threads

  1. How to read different data segments from a text file?
    By alutchman in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 18th, 2013, 01:35 PM
  2. Using for loop to read in data from text file using Scanner class
    By Scippi in forum Loops & Control Statements
    Replies: 23
    Last Post: February 26th, 2013, 10:53 PM
  3. Read and write to a text file and calculate values
    By s.sariyan in forum What's Wrong With My Code?
    Replies: 19
    Last Post: November 28th, 2012, 10:19 AM
  4. Replies: 8
    Last Post: March 25th, 2011, 02:34 PM
  5. Read data from text file
    By yroll in forum Algorithms & Recursion
    Replies: 4
    Last Post: December 31st, 2009, 01:40 AM