Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By pbrockway2

Thread: Help with add Customer application

  1. #1
    Ciggy is offline Member
    Join Date
    Apr 2012
    Posts
    3
    Rep Power
    0

    Default Help with add Customer application

    I am currently in a Java class and the class has been pretty simple. We have learned a lot of stuff but for the course project we are assumed to find information on our own about things we can not already do to make a full program for the last grade. The way I want things to function should get me an A+ and i've spent a lot of time with it.

    My problem is that when I add a new customer to the text file it automatically generates a custID. I want this to start from 1 and continue over and over. This works great, until you restart the program. Then the program restarts at 1 and the text file goes from 1, 2, 3, 4, 5 back to 1 because the program's first input starts at 1. I want to read from the last line in the text file first integer custID set the custID to that number then when a new customer is added continue to +1.

    The text file strings look like so "1, Name, Email, Phone, City, Street; " whats in between the quotes is what is printed on each line, with what the user has input.

    Here is the code that is adding this information to the file.

    Java Code:
    package Pool_Tub_Calc;
    
    import javax.swing.*;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.Document;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class AddCust extends JPanel implements ActionListener{
    	
    	int cuID = 0;
    		
    	boolean flag = false;
    	boolean dirFlag = false;
    	
    	JLabel custHeadLb = new JLabel("<html><body style='width:350px;'><center><h3>Save Customer Information</h3></center></body></html>");
    	
    	
    	JLabel custNameLb = new JLabel("Name: ");
    	JLabel custEmailLb = new JLabel("Email: ");
    	JLabel custPhoneLb = new JLabel("Phone: ");
    	JLabel custCityLb = new JLabel("City: ");
    	JLabel custStreetLb = new JLabel("Street: ");
    	JLabel custSelectLb = new JLabel("Select Existing Customer: ");
    	
    	JTextField custNameTf = new JTextField("", 20);
    	JTextField custEmailTf = new JTextField();
    	JTextField custPhoneTf = new JTextField("Example: 123-123-1234");
    	JTextField custCityTf = new JTextField();
    	JTextField custStreetTf = new JTextField();
    	JTextField custDropTf = new JTextField(); //place holder for dropdown box
    		
    	
    	JButton custClear = new JButton("Clear");
    	JButton custSave = new JButton("Save");
    	JButton custEdit = new JButton("Edit");
    	JButton custDelete = new JButton("Delete Customer");
    	
    	String custName, custEmail, custPhone, custCity, custStreet;
    	
    	
    	
    	
    	public AddCust(){
    	
    		//create panels for layout
    		JPanel custHead = new JPanel();
    		JPanel custLabels = new JPanel();
    		JPanel custInputs = new JPanel();
    		JPanel custButtons = new JPanel();
    		JPanel custFoot = new JPanel();
    		
    		//add panels to containers
    		this.add(custHead, BorderLayout.NORTH);
    		this.add(custLabels, BorderLayout.WEST);
    		this.add(custInputs, BorderLayout.CENTER);
    		this.add(custButtons, BorderLayout.EAST);
    		this.add(custFoot, BorderLayout.SOUTH);
    		
    		//add components to panels
    		custHead.setLayout(new FlowLayout());
    		custHead.add(custHeadLb);
    		
    		custLabels.setLayout(new GridLayout(5,1,10,10));
    		custLabels.add(custNameLb);
    		custLabels.add(custEmailLb);
    		custLabels.add(custPhoneLb);
    		custLabels.add(custCityLb);
    		custLabels.add(custStreetLb);
    		
    		custInputs.setLayout(new GridLayout(5,1,5,5));
    		custInputs.add(custNameTf);
    		custInputs.add(custEmailTf);
    		custInputs.add(custPhoneTf);
    		custInputs.add(custCityTf);
    		custInputs.add(custStreetTf);
    		
    		custButtons.setLayout(new GridLayout(2,1,5,5));
    		custButtons.add(custSave);
    		custButtons.add(custClear);
    		
    		custFoot.setLayout(new GridLayout(1,3,5,5));
    		custFoot.add(custSelectLb);
    		custFoot.add(custDropTf);
    		custFoot.add(custEdit);
    		
    		//save button is default set to disabled unless form is complete
    		custSave.setEnabled(false);
    		
    		
    		//add action listeners
    		custNameTf.addActionListener(this);
    		custEmailTf.addActionListener(this);
    		custPhoneTf.addActionListener(this);
    		custCityTf.addActionListener(this);
    		custStreetTf.addActionListener(this);
    		custClear.addActionListener(this);
    		custSave.addActionListener(this);
    		custEdit.addActionListener(this);
    		custDelete.addActionListener(this);
    		
    		//create file on system
    		File customersFile = new File("customers.txt");
    		try {
    		    flag = customersFile.createNewFile();
    		} 
    		catch (IOException ioe) {
    		     System.out.println("Error while Creating File in Java " + ioe);
    		}
    		
    		//enable submit button
    		Document nameDoc;
    		Document emailDoc;
    		Document phoneDoc;
    		Document cityDoc;
    		Document streetDoc;
    		nameDoc = custNameTf.getDocument();
    		emailDoc = custEmailTf.getDocument();
    		phoneDoc = custPhoneTf.getDocument();
    		cityDoc = custCityTf.getDocument();
    		streetDoc = custStreetTf.getDocument();
    		
    		nameDoc.addDocumentListener(new SubmitController(custSave));
    		emailDoc.addDocumentListener(new SubmitController(custSave));
    		phoneDoc.addDocumentListener(new SubmitController(custSave));
    		cityDoc.addDocumentListener(new SubmitController(custSave));
    		streetDoc.addDocumentListener(new SubmitController(custSave));
    
    	}
    	
    	class SubmitController implements DocumentListener {
    	    private JButton custSave;
    
    	    SubmitController(JButton b) {
    	    		custSave = b;
    	    }
    
    	    public void changedUpdate(DocumentEvent e) {
    	        disableIfEmpty(e);
    	    }
    
    	    public void insertUpdate(DocumentEvent e){
    	        disableIfEmpty(e);
    	    }
    
    	    public void removeUpdate(DocumentEvent e){
    	        disableIfEmpty(e);
    	    }
    
    	    public void disableIfEmpty(DocumentEvent e) {
    	        if(custNameTf.getText().length() == 0 && custEmailTf.getText().length() == 0 && custPhoneTf.getText().length() == 0 && custCityTf.getText().length() == 0 && custStreetTf.getText().length() == 0){
    				custSave.setEnabled(false);
    			}
    
    			if(custNameTf.getText().length() > 0 && custEmailTf.getText().length() > 0 && custCityTf.getText().length() > 0 && custStreetTf.getText().length() > 0){
    				if(custPhoneTf.getText().length() == 12)
    				custSave.setEnabled(true);
    			}
    	    }
    	}
    	
    	
    	public void actionPerformed(ActionEvent e){
    		
    		
    		if(e.getSource() == custSave){
    						
    			String validEmail = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    			Pattern compare = Pattern.compile(validEmail, Pattern.CASE_INSENSITIVE);
    			Matcher matcher = compare.matcher(custEmailTf.getText());
    				if(matcher.matches()){
    					cuID += 1;
    					String na = custNameTf.getText();
    					String em = custEmailTf.getText();
    					String ph = custPhoneTf.getText();
    					String ci = custCityTf.getText();
    					String st = custStreetTf.getText();
    			
    					Customer cu = new Customer(cuID, na, em, ph, ci, st);
    			
    					FileWriter fw = null;
    					BufferedWriter bw = null;
    					
    			
    					try{
    						fw = new FileWriter("customers.txt", true);
    						bw = new BufferedWriter(fw);
    						bw.append(cu.toString());
    						bw.newLine();
    						bw.close();
    				
    						//show saved confirm pop up
    						JOptionPane.showMessageDialog(null, ("Customer information has been saved! CustID: #" + cuID));
    				
    						//clear out information because it has been saved.
    						custNameTf.setText("");
    						custEmailTf.setText("");
    						custPhoneTf.setText("Example: 123-123-1234");
    						custCityTf.setText("");
    						custStreetTf.setText("");
    						
    						custSave.setEnabled(false);
    				
    					}
    					catch(IOException ioe){
    						System.out.println(ioe.getMessage());
    					}	
    			}
    				else{
    					JOptionPane.showMessageDialog(null, "Please enter a valid email address.");				
    				}
    			
    		}
    		
    		if(e.getSource() == custClear){
    			custNameTf.setText("");
    			custEmailTf.setText("");
    			custPhoneTf.setText("Example: 123-123-1234");
    			custCityTf.setText("");
    			custStreetTf.setText("");			
    		}	
    	}
    }


    Thanks in advance for help I will provide any information needed to assist me getting this to work.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Help with add Customer application

    Suggestions:
    • Split up the god-class above into several smaller classes, each focusing on a single purpose. It's a whole lot easier fixing well separated small classes than trying to fix one huge complex g'mish of code. It's a whole lot easier for us to understand what you're doing and be able to help you if you make these changes.
    • In particular your GUI or view code should not do any file I&O which should be in its own class
    • And you should have a Customer class that encapsulates the concept of a customer and his properties.
    • And you should have a database or Customer collection class that holds the Customer objects, perhaps in an ArrayList. The GUI can iterate through this collection for display, can add to it and remove from it.
    • The I&O classes can read from a file to add Customers to the CustomerCollection class.
    • Likely the CustomerCollection will keep track of customerId values and possibly create new id's for new Customer objects added to it.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Help with add Customer application

    I want to read from the last line in the text file first integer custID set the custID to that number then when a new customer is added continue to +1.
    Can't you just do that?

    What I mean is where you have "//create file on system" instead *check* for existence of the file. If it exists read it, set cuID and close it again. If it does not exist, create it. From that point on you should be good: the file will exist and cuID will have the appropriate value.

    A separate point, but it strikes me that you have rather a lot in the panel's constructor. Perhaps some other class could represent the collection of customers? This other class class could be responsible for the logic of locating/creating the file and knowing what ID to assign a new customer. [Edit] continue down this track and you eventually end up at Fubarable's excellent advice...
    Last edited by pbrockway2; 04-10-2012 at 12:05 AM.
    Fubarable likes this.

  4. #4
    Ciggy is offline Member
    Join Date
    Apr 2012
    Posts
    3
    Rep Power
    0

    Default Re: Help with add Customer application

    Quote Originally Posted by pbrockway2 View Post
    Can't you just do that?

    What I mean is where you have "//create file on system" instead *check* for existence of the file. If it exists read it, set cuID and close it again. If it does not exist, create it. From that point on you should be good: the file will exist and cuID will have the appropriate value.

    A separate point, but it strikes me that you have rather a lot in the panel's constructor. Perhaps some other class could represent the collection of customers? This other class class could be responsible for the logic of locating/creating the file and knowing what ID to assign a new customer. [Edit] continue down this track and you eventually end up at Fubarable's excellent advice...

    Thank you both for your replys and help! I am new to Java and it isnt exactly my major but I do understand there are coding ethics I should be following. I have been getting a bit messy with my class. I do actually have a Customer class that creates the customer object and formats it to ID, name, phone, email, city, street;

    Yes checking for the file then reading the ID to set it would work perfect! I understand the logic behind it but the answer im looking for is how to skim through text files to pull information out. Like I need to command the program to find the last line of the file and then only pull the first part of the string before the , to get just the last customerID number. I have no idea how to do this.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Help with add Customer application

    I need to command the program to find the last line of the file
    If you want to do this I don't think there is any shortcut: read each line of the file (BufferedReader has a readLine() method) until there are no more.

    and then only pull the first part of the string before the , to get just the last customerID number
    Use the string methods indexOf() and substring().

  6. #6
    Ciggy is offline Member
    Join Date
    Apr 2012
    Posts
    3
    Rep Power
    0

    Default Re: Help with add Customer application

    Quote Originally Posted by pbrockway2 View Post
    If you want to do this I don't think there is any shortcut: read each line of the file (BufferedReader has a readLine() method) until there are no more.



    Use the string methods indexOf() and substring().


    Thank you!! I got this to work!

    Java Code:
    //create file on system
    		File customersFile = new File("customers.txt");
    		if(customersFile.exists()){
    			try {
    				InputStreamReader streamReader = new InputStreamReader(new FileInputStream(customersFile));
    				BufferedReader bfr = new BufferedReader(streamReader);
    				String line = new String();
    				try {
    					while(bfr.ready()){
    						line = bfr.readLine();
    					}
    				} catch (IOException e3) {
    					e3.printStackTrace();
    				}
    			
    				cuID = Integer.parseInt(line.substring(0, line.indexOf(",")));
    				
    			} catch (FileNotFoundException e2) {
    				e2.printStackTrace();
    			}
    			
    		}
    		else{
    			try {
    				flag = customersFile.createNewFile();
    			} 
    			catch (IOException ioe) {
    				System.out.println("Error while Creating File in Java " + ioe);
    			}
    		}

Similar Threads

  1. Replies: 0
    Last Post: 11-25-2010, 12:05 PM
  2. [Ljava.lang.Object; cannot be cast to domain.Customer
    By niteangell21 in forum New To Java
    Replies: 7
    Last Post: 09-26-2010, 08:38 PM
  3. Replies: 1
    Last Post: 08-05-2009, 02:43 AM
  4. a Queue of customer in the GUI
    By jonywalker123 in forum Advanced Java
    Replies: 2
    Last Post: 02-26-2009, 11:02 PM
  5. Validating the customer type, the subtotal,
    By wisdom4542002 in forum New To Java
    Replies: 0
    Last Post: 10-28-2008, 06:12 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •