I am trying to do a primary key so that each member can't hava the same ID and if th same ID is entered an error is give. Can someone please help me cause I can't do it at all.Thank you.

static void addMember(ArrayList<GymUser> UserListIn)
    {


        String tempUserrID;
        String tempID;
        String tempName;
        String tempSurname;
        int tempAge;
        String tempAddress;
        int tempPhone;
        String tempDuration;
        Scanner keyboard = new Scanner(System.in);
        keyboard.useDelimiter("\n");
        System.out.println("Please enter the member's Personal Details");
        System.out.println("-------------------- ");
        System.out.println("Enter the mebership number");
        tempUserrID = keyboard.next();
        System.out.print("Enter the ID no.: ");
        tempID = keyboard.next();
        System.out.print("Enter Name: ");
        tempName = keyboard.next();
        System.out.print("Enter Surname:");
        tempSurname = keyboard.next();
        System.out.print("Enter Address:");
        tempAddress = keyboard.next();
        System.out.print("Enter Age:");
        tempAge = keyboard.nextInt();
        System.out.print("Enter Phone:");
        tempPhone = keyboard.nextInt();
        System.out.print("MemberShip Duration:");
        tempDuration = keyboard.next();
        UserListIn.add(new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration));
        
       
    }

Recommended Answers

All 46 Replies

Inside the: UserListIn.add(GymUser newGymUser) method you will take the new Gym User and compare him with the other gymUsers. If one with the same id already exists then don't add him and print a message or throw an Exception.
If you don't want to make this check inside the .add method, then before calling it, take all the other users and compare them with the new user. If the new user doesn't have the same id, then call your method.
By the way, if you are using a database, and the table already is created with a primary key then you don't need to check anything because an SQLException will be thrown and the new user won't be inserted

No for this database I am using java. I know database are generally coded with SQL but in my assigment I need to use java. Can you help me a bit in the coding and where to put it because I'm still a beginner with this type of coding. Thank you very much javaAddict.

I suppose you could just use a HashMap

I already told you where to put it. Just create a method that returns boolean and has a GymUser argument, that checks whether the input gymUser's id already exists among the other users that are already stored. By the way, where do you store the other users?(ArrayList, Vector?)

GymUser newGymUser = new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration);
boolean b = alreadyExists(newGymUser );
if (b) {
  System.out.println("Cannot insert existing user");
} else {
 UserListIn.add(newGymUser );
}

I don't know how to use hash maps. I'm that good in java. All I want to do I think is to compare the allready saved ID no to the new ID being inputted. But I'don't know how to code the thing and where to place it.

In an array List.

I've done this till now from the help given form you both. But now if I will have an error (cannot find symbol - variable newGymUser). I am storing these users in an array list. Thank you very much javaAddict....but I'm still having errors.Can oyu help me pls. Thanks

static void addMember(ArrayList<GymUser> UserListIn)
    {
        String tempUserrID;
        String tempID;
        String tempName;
        String tempSurname;
        int tempAge;
        String tempAddress;
        int tempPhone;
        String tempDuration;
        Scanner keyboard = new Scanner(System.in);
        keyboard.useDelimiter("\n");
        System.out.println("Please enter the member's Personal Details");
        System.out.println("-------------------- ");
        System.out.println("Enter the mebership number");
        tempUserrID = keyboard.next();
        System.out.print("Enter the ID no.: ");
        tempID = keyboard.next();
        System.out.print("Enter Name: ");
        tempName = keyboard.next();
        System.out.print("Enter Surname:");
        tempSurname = keyboard.next();
        System.out.print("Enter Address:");
        tempAddress = keyboard.next();
        System.out.print("Enter Age:");
        tempAge = keyboard.nextInt();
        System.out.print("Enter Phone:");
        tempPhone = keyboard.nextInt();
        System.out.print("MemberShip Duration:");
        tempDuration = keyboard.next();
        UserListIn.add(new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration));
        

        boolean b = alreadyExists(newGymUser );     /error here
        if (b) {
                    System.out.println("Cannot insert existing user");
                } else 
                {
                        UserListIn.add(newGymUser );
                }
                GymUser newGymUser = new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration);
                boolean b = alreadyExists(newGymUser );
                if (b) {
                            System.out.println("Cannot insert existing user");
                        } else 
                        {
                            UserListIn.add(newGymUser );
                        }

       
    }

Sorry asking many quest but,it means that I need the comparing..(those few coding that you gave me) before adding in the array list? Thanks

Can't you READ??? First you create a new object, then call the alreadyExists, and then call add.
You are calling add and then you are calling the alreadyExist and then you are doing another add. Does this make sense to you? By the way you are not creating the newGymUser object.

You have to implement the alreadyExists.

You have to create a global ArrayList where you will store the Gym Users objects

I will add some more code after a few hours, with better explanations

Thank you javaAddict. Sorry for asking many questions but I am still learning. At the moment I will try to follow your steps till you can explain me better. Thank you.

I tried to do this but it's still not the way it should be. Having problems with (cannot find symbol- method already exists java.lang.string)Can you help with this pls? Thank you very much.

static void addMember(ArrayList<GymUser> UserListIn)
    {

        String tempUserrID;
        String tempID;
        String tempName;
        String tempSurname;
        int tempAge;
        String tempAddress;
        int tempPhone;
        String tempDuration;
        Scanner keyboard = new Scanner(System.in);
        keyboard.useDelimiter("\n");
        System.out.println("Please enter the member's Personal Details");
        System.out.println("-------------------- ");
        System.out.println("Enter the mebership number");
        tempUserrID = keyboard.next();
        System.out.print("Enter the ID no.: ");
        tempID = keyboard.next();
        System.out.print("Enter Name: ");
        tempName = keyboard.next();
        System.out.print("Enter Surname:");
        tempSurname = keyboard.next();
        System.out.print("Enter Address:");
        tempAddress = keyboard.next();
        System.out.print("Enter Age:");
        tempAge = keyboard.nextInt();
        System.out.print("Enter Phone:");
        tempPhone = keyboard.nextInt();
        System.out.print("MemberShip Duration:");
        tempDuration = keyboard.next();
       
         Object  newGymUser = new Object();
        
          boolean b = alreadyExists(newGymUser );   //error here
        if (b) {
                    System.out.println("Cannot insert existing user");
                } else 
                {
                        UserListIn.add(newGymUser );
                }
                GymUser newGymUser = new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration);
                boolean b = alreadyExists(newGymUser );
                if (b) {
                            System.out.println("Cannot insert existing user");
                        } else 
                        {
                            UserListIn.add(newGymUser );
                        }

        
        
        
        
        UserListIn.add(new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration));
        
      
       
    }

Of course there is an error - you haven't written the method alreadyExists() yet. That is exactly what javaAddict was trying to tell you in the first place. You can't call methods that you haven't written yet.

Additionally, if you would actually read the API for HashMap, which Phaelex suggested, you would see that it has a method to see if a given key already exists, which makes it even easier on you.

If there is a requirement that you use ArrayList for an assignment, fine, that's valid. But if you're avoiding HashMap just because you don't know how to use it, that's just stubborn, lazy and ignorant.

Here is a sample of your code:

Object  newGymUser = new Object();
        
          boolean b = alreadyExists(newGymUser );   //error here
        if (b) {
                    System.out.println("Cannot insert existing user");
                } else 
                {
                        UserListIn.add(newGymUser );
                }
                GymUser newGymUser = new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration);
                boolean b = alreadyExists(newGymUser );
                if (b) {
                            System.out.println("Cannot insert existing user");
                        } else 
                        {
                            UserListIn.add(newGymUser );
                       }
        
        UserListIn.add(new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration));

Why do you call UserListIn.add() 3 times??????????????

And what is this: Object newGymUser = new Object();
The object is GymUser

Don't you understand what are you writing?
You are creating a new Object: Object newGymUser = new Object(); Checking if it exists in order to add it or not, AND then you do the same thing with :GymUser newGymUser = new GymUser(.....);
And after you are done, again you are calling the add.

Just create ONE object: GymUser newGymUser = new GymUser(.....); with arguments the ones that you have from the keyboard, and check this if it exists or not in order to add it.
And do it once.

I would suggest that you implement the bollean alreadyExists(GymUser user) in the class UserListIn. And if you are going to use ArrayList, or HashTable declare it in UserList and use methods to access it: like you are doing with add()

Sorry that was not my exact code.I copied it twice by mistake. Now I think I have to write a method alreadyExists...yes? I've done the following:

static void addMember(ArrayList<GymUser> UserListIn)
    {

        String tempUserrID;
        String tempID;
        String tempName;
        String tempSurname;
        int tempAge;
        String tempAddress;
        int tempPhone;
        String tempDuration;
        Scanner keyboard = new Scanner(System.in);
        keyboard.useDelimiter("\n");
        System.out.println("Please enter the member's Personal Details");
        System.out.println("-------------------- ");
        System.out.println("Enter the mebership number");
        tempUserrID = keyboard.next();
        System.out.print("Enter the ID no.: ");
        tempID = keyboard.next();
        System.out.print("Enter Name: ");
        tempName = keyboard.next();
        System.out.print("Enter Surname:");
        tempSurname = keyboard.next();
        System.out.print("Enter Address:");
        tempAddress = keyboard.next();
        System.out.print("Enter Age:");
        tempAge = keyboard.nextInt();
        System.out.print("Enter Phone:");
        tempPhone = keyboard.nextInt();
        System.out.print("MemberShip Duration:");
        tempDuration = keyboard.next();
       

        
          boolean b = alreadyExists(newGymUser );
        if (b) {
                    System.out.println("Cannot insert existing user");
                } else 
                {
                        UserListIn.add(newGymUser );
                }
                
         GymUser newGymUser = new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration);
                
        
        
        
        
        UserListIn.add(new GymUser(tempUserrID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration));
        
      
       
    }

Sorry I Changed the code a bit. Now I modified it as follows:

static void addMember(ArrayList<GymUser> UserListIn)
    {

        String tempUserrID;
        String tempID;
        String tempName;
        String tempSurname;
        int tempAge;
        String tempAddress;
        int tempPhone;
        String tempDuration;
        Scanner keyboard = new Scanner(System.in);
        keyboard.useDelimiter("\n");
        System.out.println("Please enter the member's Personal Details");
        System.out.println("-------------------- ");
        System.out.println("Enter the mebership number");
        tempUserrID = keyboard.next();
        System.out.print("Enter the ID no.: ");
        tempID = keyboard.next();
        System.out.print("Enter Name: ");
        tempName = keyboard.next();
        System.out.print("Enter Surname:");
        tempSurname = keyboard.next();
        System.out.print("Enter Address:");
        tempAddress = keyboard.next();
        System.out.print("Enter Age:");
        tempAge = keyboard.nextInt();
        System.out.print("Enter Phone:");
        tempPhone = keyboard.nextInt();
        System.out.print("MemberShip Duration:");
        tempDuration = keyboard.next();
       

        GymUser newGymUser = new GymUser(tempID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration); 
        
          boolean b = getID(newGymUser );
        if (b) {
                    System.out.println("Cannot insert existing user");
                } else 
                {
                        UserListIn.add(newGymUser );
                }

      
       
    }

people I have this code in these class. I've now implemented the alreadyExists method but I don't know if it is correct. Now I am having an error in the same palce as before (cannot find symbol - method alreadyExist(GymUser) ) Can some please help me because I am really confused about this logic. Pls help me a bit. I know some of you are saying that they've already fed up helping me but I am really confused .Thanks.

/**
 * This class contains instance variables and method(members)
 * 
 */
import java.io.*;
public class GymUser implements Serializable
{
        //these are instance variables
            public String myPrimaryKeyField;

        private String m_UserrID;
        private String m_UserName;
        private String m_UserID;
        private String m_UserSurname;
        private String m_UserAddress;
        private int m_UserPhone;
        private int m_UserAge;
        private String m_UserDuration;
        
        //this is the constructor
        public GymUser(String UserrID,String UserName,String UserID,String UserSurname, String UserAddress, int UserPhone, int UserAge,String UserDuration)
        {
            m_UserrID =  UserrID;
            m_UserName = UserName;
            m_UserSurname = UserSurname;
            m_UserAddress = UserAddress;
            m_UserPhone = UserPhone;
            m_UserAge= UserAge;
            m_UserID = UserID;
            m_UserDuration = UserDuration;
        }
   public boolean alreadyExists (Object object)
    {
        if (this == object)
        {
            return true;
        }
         if (this != object)
        {
            return false;
        }
        
        GymUser other=(GymUser)object;
        return this.myPrimaryKeyField.equals(other.myPrimaryKeyField);



    }

This is the other class.

import java.io.*;         // required for handling the IOExceptions
import java.util.*;

class ManipulateGymUser
{
     // create an empty list to hold Cars
     ArrayList<GymUser> UserListIn = new ArrayList<GymUser>()
    static void addMember(ArrayList<GymUser> UserListIn)
    {

        String tempUserrID;
        String tempID;
        String tempName;
        String tempSurname;
        int tempAge;
        String tempAddress;
        int tempPhone;
        String tempDuration;
        Scanner keyboard = new Scanner(System.in);
        keyboard.useDelimiter("\n");
        System.out.println("Please enter the member's Personal Details");
        System.out.println("-------------------- ");
        System.out.println("Enter the mebership number");
        tempUserrID = keyboard.next();
        System.out.print("Enter the ID no.: ");
        tempID = keyboard.next();
        System.out.print("Enter Name: ");
        tempName = keyboard.next();
        System.out.print("Enter Surname:");
        tempSurname = keyboard.next();
        System.out.print("Enter Address:");
        tempAddress = keyboard.next();
        System.out.print("Enter Age:");
        tempAge = keyboard.nextInt();
        System.out.print("Enter Phone:");
        tempPhone = keyboard.nextInt();
        System.out.print("MemberShip Duration:");
        tempDuration = keyboard.next();
       

        GymUser newGymUser = new GymUser(tempID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration); 
        
          boolean b = alreadyExists(newGymUser );
        if (b) {
                    System.out.println("Cannot insert existing user");
                } else 
                {
                        UserListIn.add(newGymUser );
                }
}

That method does not remotely resemble what javaAddict explained. The method needs to loop through the entries in your collection checking each ID. If one of them has that ID then it should return true.

Sorry Ezzaral but I think I'm not thinking and panicking or I am a big ignorant in java. I can't even understand how I am going to do the for loop in this method and after wards avoid that error in the other class. I am really pressed in time to handle this assigment and the primary key is giving me a lot of trouble. Can you give me some code examples of loop through the entries Please! Thank you very much for your patience.

There is nothing special about the loop. You just need a plain old for() loop over all of the entries

int idToFind=999;  // example value
for (int i=0; i<list.size(); i++){
  Entry listEntry = (Entry) list.get(i);
  if (listEntry.getId() == idToFind){
    return true;
  }
}
return false;

Obviously, you need to use your own parameter and class type values (not Entry) for the comparison. This is also the "old-fashioned" way to do it with explicit casting. With generics and the for-each loop there is even less to it

int idToFind=999;  // example value
for (Entry listEntry : list){
  if (listEntry.getId() == idToFind){
    return true;
  }
}
return false;

I don't know if I am doing the correct thing as you told me. This method must be implemented in the class that contains all methods and constructors..right? But I am still confused and making a mess.

/**
 * This class contains instance variables and method(members)
 * 
 */
import java.io.*;
public class GymUser implements Serializable
{
        //these are instance variables
            public String myPrimaryKeyField;

        private String m_UserrID;
        private String m_UserName;
        private String m_UserID;
        private String m_UserSurname;
        private String m_UserAddress;
        private int m_UserPhone;
        private int m_UserAge;
        private String m_UserDuration;
        
        //this is the constructor
        public GymUser(String UserrID,String UserName,String UserID,String UserSurname, String UserAddress, int UserPhone, int UserAge,String UserDuration)
        {
            m_UserrID =  UserrID;
            m_UserName = UserName;
            m_UserSurname = UserSurname;
            m_UserAddress = UserAddress;
            m_UserPhone = UserPhone;
            m_UserAge= UserAge;
            m_UserID = UserID;
            m_UserDuration = UserDuration;
        }


         public boolean alreadyExists (Object object)
    {
         
    for(GymUser listEntry : UserListIn)
    {  if (listEntry.getId() == m_UserrID)
        {    return true;  }
    }return false;
}
 /* if (this == object)
        {
            return true;
        }
         if (this != object)
        {
            return false;
        }
        
        GymUser other=(GymUser)object;
        return this.myPrimaryKeyField.equals(other.myPrimaryKeyField);

*/

}

You don't want to compare the list entry against "m_UserrID", you need to compare it against the id value from the parameter that you passed to the method.

That method should also be declared in whatever class has your "UserListIn" list. It doesn't really have anything to do with the definition of a gym user.

Ezzaral sorry for asking many questions but I am still a young student and I am shacky with java. Can you give me examples with my own code cause I am really confused. If've mannaged to do almost my whoe assigment and now I am stuck in this primary key section. Can you show me using my own code what I want to do. Thank you for you're patience Ezzaral. I am really appreciating.Thanks

You very nearly have it but only need the changes I mentioned

public boolean alreadyExists(GymUser user) {
    for(GymUser listEntry : UserListIn) {
        if(listEntry.getId() == user.getId()) {
            return true;
        }
    }
    return false;
}

and that method needs to be defined in the class that contains your "UserListIn".

I've done alreadyExists method with your help.But I am having an error in the boolean part (below) and error (non-static alreadyExists(GymUser) cannot be referenced from a static context). Why am I having this error and what I need to modify pls? Thanks a lot for your help.

import java.io.*;         // required for handling the IOExceptions
import java.util.*;

class ManipulateGymUser
{
     // create an empty list to hold Cars
     ArrayList<GymUser> UserListIn = new ArrayList<GymUser>();

  public boolean alreadyExists(GymUser user)
    {
        for(GymUser listEntry : UserListIn)
        {
            if(listEntry.getID() == user.getID())
            {
                return true;
            }
        }
         return false;
    }
      // method for adding a new member to the list

    static void addMember(ArrayList<GymUser> UserListIn)
    {
  String tempUserrID;
        String tempID;
        String tempName;
        String tempSurname;
        int tempAge;
        String tempAddress;
        int tempPhone;
        String tempDuration;
        Scanner keyboard = new Scanner(System.in);
        keyboard.useDelimiter("\n");
        System.out.println("Please enter the member's Personal Details");
        System.out.println("-------------------- ");
        System.out.println("Enter the mebership number");
        tempUserrID = keyboard.next();
        System.out.print("Enter the ID no.: ");
        tempID = keyboard.next();
        System.out.print("Enter Name: ");
        tempName = keyboard.next();
        System.out.print("Enter Surname:");
        tempSurname = keyboard.next();
        System.out.print("Enter Address:");
        tempAddress = keyboard.next();
        System.out.print("Enter Age:");
        tempAge = keyboard.nextInt();
        System.out.print("Enter Phone:");
        tempPhone = keyboard.nextInt();
        System.out.print("MemberShip Duration:");
        tempDuration = keyboard.next();
       
      
        GymUser newGymUser = new GymUser(tempID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration); 
        

           boolean b = alreadyExists(newGymUser );  //error here
        if (b) {
                    System.out.println("Cannot insert existing user");
                } 
                else 
                {
                        UserListIn.add(newGymUser );
                }
}

It has to be declared static because you are calling it from within a static method. Note, making all methods static might be convenient , but it's a very bad idea as a general progamming strategy.

You should be learning to create objects and call methods on those objects, rather than writing what amounts to a procedural program with statics.

To tell you the truth I tried to make it static before but when I am making it static I am having an error (illegal start of expression). Ow I'm tired of this primary key. :) What am I doing wrong pls?

import java.io.*;         // required for handling the IOExceptions
import java.util.*;

class ManipulateGymUser
{
     // create an empty list to hold Cars
     ArrayList<GymUser> UserListIn = new ArrayList<GymUser>();
     
     public ManipulateGymUser (ArrayList<GymUser> arr)
     {
         UserListIn = arr;
     }




  

     boolean alreadyExists(GymUser user)
    {
        for(GymUser listEntry : UserListIn)
        {
            if(listEntry.getID() == user.getID())
            {
                return true;
            }
        }
         return false;
    }

      // method for adding a new member to the list

    static void addMember(ArrayList<GymUser> UserListIn)
    {


      String tempUserrID;
        String tempID;
        String tempName;
        String tempSurname;
        int tempAge;
        String tempAddress;
        int tempPhone;
        String tempDuration;
        Scanner keyboard = new Scanner(System.in);
        keyboard.useDelimiter("\n");
        System.out.println("Please enter the member's Personal Details");
        System.out.println("-------------------- ");
        System.out.println("Enter the mebership number");
        tempUserrID = keyboard.next();
        System.out.print("Enter the ID no.: ");
        tempID = keyboard.next();
        System.out.print("Enter Name: ");
        tempName = keyboard.next();
        System.out.print("Enter Surname:");
        tempSurname = keyboard.next();
        System.out.print("Enter Address:");
        tempAddress = keyboard.next();
        System.out.print("Enter Age:");
        tempAge = keyboard.nextInt();
        System.out.print("Enter Phone:");
        tempPhone = keyboard.nextInt();
        System.out.print("MemberShip Duration:");
        tempDuration = keyboard.next();
       
      
        GymUser newGymUser = new GymUser(tempID, tempName, tempID, tempSurname, tempAddress, tempPhone, tempAge,tempDuration); 
        

           static boolean b = alreadyExists(newGymUser );       //error here.
        if (b) {
                    System.out.println("Cannot insert existing user");
                } 
                else 
                {
                        UserListIn.add(newGymUser );
                }
}

I meant you have to declare the method as static, not the variable that you are using to hold the result of that method call, which is what you did above.

You should actually just remove the static declaration from the addMember() method anyway and make sure you are using an instance of ManipulateGymUser in your other code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.