Results 1 to 10 of 10
  1. #1
    Lidiya is offline Member
    Join Date
    Dec 2010
    Location
    Sweden, Stockholm
    Posts
    4
    Rep Power
    0

    Default Unique personal number

    Hi!

    I have a program where I create customers and put them in a list (ArrayList). The program has a menu where the user enters a customerīs name and a personal id through standard input. I want that customers should have unique personal id (you can not put two people with the same id).
    I have a problem to determine how to check that the person I insert does not have the same number to those already in the list.

    System.out.println ("Customerīs name:");
    String name = scan.nextLine ();
    String id;

    try {

    System.out.println ("Customerīs id:");
    String id = scan.nextLine();

    // Creates a customer
    customer = new Customer (name, id);

    // Loops through the list to see if there is a persons with the same id
    for (int i = 0; i <customers.size (); i ++) {
    if (customers.get (i). getID (). equals (id)) {
    customer = customers.get (i);
    System.out.println ("ID must be unique!");
    }
    }

    else {
    customers.add (customer);
    }
    } catch (Exception e) {
    System.out.println (e);
    }
    break;

    Thanks for all help!

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,993
    Rep Power
    9

    Default

    When posting code, make sure you use code tags and post the code as an SSCCE.

    What problem are you having? What happens when you run the code? What were you expecting? Be specific.

    How would you do this "by hand"? Write out instructions, without worrying about code, specifically listing the steps you would take to do this. When you have that done, it should be pretty easy to convert to code.

  3. #3
    lovelesh is offline Senior Member
    Join Date
    Nov 2010
    Location
    Delhi
    Posts
    135
    Blog Entries
    1
    Rep Power
    0

    Default

    Is there any specific reason for using Arraylist for storing?

    Hashmap suits best for these kind of requirements. Or use Hashtable if the program is multithreaded.

  4. #4
    Lidiya is offline Member
    Join Date
    Dec 2010
    Location
    Sweden, Stockholm
    Posts
    4
    Rep Power
    0

    Default

    No, there are no special reasons for using ArrayList. I am just more familiar with this kind of lists and feel more comfortable to use it :)

  5. #5
    demonick is offline Member
    Join Date
    Dec 2010
    Posts
    27
    Rep Power
    0

    Default

    Why not use HashSet? Supports Value, Key pairs and unique values.

  6. #6
    Lidiya is offline Member
    Join Date
    Dec 2010
    Location
    Sweden, Stockholm
    Posts
    4
    Rep Power
    0

    Default

    XML Code:
    [CODE]/*
           *  Create a person
           *  Watch, if there is a person in a list with the same id as the person that is created
           *  If true, write out a message that id should be unique
           *  Otherwise put a person in a list
           */
    
            System.out.print("Customerīs name: ");
    	String aName = scan.nextLine();
    	String id;
    	
            try {
    	    System.out.print("Customerīs id: ");
    	    id = scan.nextLine();
    	    customer = new Customer(aName, id);
    	
            for (int i = 0; i < customers.size(); i++) 
    	     if (customers.get(i).getId().equals(id))
    	          System.out.println("Id should be unique!");
                        else 
    			customers.add(customer);
    	
    	  } catch (Exception e) {
    		System.out.println(e);
    	  }[/CODE]
    It does not even go to put a customer in a list....
    Some problem with a logic?

  7. #7
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    The problem with the logic, is that if customers is empty, then there is no path that adds new entries into it.

    You really should consider using a set instead of an arraylist, or if the only thing your Customer class does is act as a container for a name and ID, then a map would simplify things even more.

    Java Code:
    HashMap<string, string> customers = new HashMap<string, string>();
    
    ...scanner code...
    
    if(customers.get(id) == null) 
      customers.put(id, name);
    else
      System.out.println("Id should be unique!");
    ...doesn't that seem simpler?

  8. #8
    Lidiya is offline Member
    Join Date
    Dec 2010
    Location
    Sweden, Stockholm
    Posts
    4
    Rep Power
    0

    Default

    Quote Originally Posted by toadaly View Post
    The problem with the logic, is that if customers is empty, then there is no path that adds new entries into it.

    You really should consider using a set instead of an arraylist, or if the only thing your Customer class does is act as a container for a name and ID, then a map would simplify things even more.

    Java Code:
    HashMap<string, string> customers = new HashMap<string, string>();
    
    ...scanner code...
    
    if(customers.get(id) == null) 
      customers.put(id, name);
    else
      System.out.println("Id should be unique!");
    ...doesn't that seem simpler?
    Ok, HashMap, HashSet might be better to use but I have implemented the program with ArrayList. The program is not so complicated, I have a Customer class, an Account class and a class with a menu, where there are different alternatives like to create a customer, to create accounts for him, to write out information about a customer. I have implemented it with ArrayList and I would not like to change it. When I put customers into the list, I need that each customer has a unique id, i.e. there can not be 2 customers with the same id.
    Java Code:
    case 1: .....
    case 2: // Create a customer
       System.out.print("Customerīs name: ");
       String name = scan.nextLine();
       String id;
    				  
       try {
    	System.out.print("Customerīs id: ");
    	id = scan.nextLine();
    					
    	for (int i = 0; i < customers.size(); i++) 
                if (!(customers.get(i).getId().equals(id))||
    	(customers.size() == 0)){
    	        Customer customer = new Customer(name, id);
    		customers.add(customer);
    	   }
    	   else if (customers.get(i).getId().equals(id))
    		System.out.println("Id should be unique!");		
    					
    	 } catch (Exception e) {
    			System.out.println(e);
    	}
    	break;
    case 3: ...
    A customer can be added to the list only if the list is empty or if there is no person with the same id in the list, otherwise if there is a customer with the same id, the message should be written. But why does not it work to add any customer? Some advices, please...

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,658
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Lidiya View Post
    It does not even go to put a customer in a list....
    Some problem with a logic?
    Yep, suppose the List is empty; a potentially correct customer could be stored in that list but it won't because the body of the loop is never executed (and that's where your customer is added to the list). Also, your indentation is misleading, please correct that as well. Tip: create a separate little method that tests whether or not an ID is already present in the list and returns true/false accordingly.

    kind regards,

    Jos
    Last edited by JosAH; 12-26-2010 at 08:33 AM.
    cenosillicaphobia: the fear for an empty beer glass

  10. #10
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    6

    Default

    some weeks ago i had exactly the same problems, but with lottery numbers. look at the following code

    Java Code:
    import java.util.HashSet;
    import java.util.Iterator;
    
    public class HashSetExample {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		HashSet<Integer> set = new HashSet<Integer>(10);
    		int doubletten = 0;
    		// generate six lottery numbers 
    		while (set.size() < 6) {
    			int num = (int)(Math.random() * 45) + 1;
    			if (!set.add(new Integer(num))) {
    				doubletten++;
    			}
    		}
    		// print the lottery numbers
    		System.out.println("the lottery numbers are:");
    		Iterator it = set.iterator();
    		while (it.hasNext()) {
    			System.out.println(((Integer)it.next()).toString());
    		}
    		System.out.println("ingnored doubles: " + doubletten);
    	}
    
    }

    the code is generating six distinct lottery numbers out of 1 to 45. the core of the code is the line with (!set.add(new Integer(num))). since the add() method returns false when the num is already in the hashset this is a very efficient way to check for doubles with a single if statement! apply this code to your customer.
    Last edited by j2me64; 12-27-2010 at 12:15 PM.

Similar Threads

  1. How to set the unique color for windows and Mac os
    By prasad.vara in forum AWT / Swing
    Replies: 0
    Last Post: 12-03-2010, 10:55 AM
  2. Encrypting unique columns
    By andy16 in forum JDBC
    Replies: 0
    Last Post: 05-26-2010, 07:57 PM
  3. countin unique chars !
    By pauser in forum New To Java
    Replies: 4
    Last Post: 04-27-2010, 04:07 PM
  4. Generate unique letters
    By bl00dr3d in forum New To Java
    Replies: 22
    Last Post: 04-10-2009, 02:44 PM
  5. Unique element in an array
    By revathi17 in forum New To Java
    Replies: 2
    Last Post: 12-31-2007, 08:44 AM

Posting Permissions

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