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

Thread: Need some help with removing and finding items from an ArrayList

  1. #1
    Member
    Join Date
    Apr 2012
    Posts
    42
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Default Need some help with removing and finding items from an ArrayList

    I can't seem to get my program to remove the object that appears at a certain index of my ArrayList, nor can I use a search method and display an object at a certain index in my ArrayList. My program is meant to add a new employee to the arraylist if they don't already exist, and then have the options to remove an employee, find an employee, print out everything from the arraylist, and then quit. I think there may be something wrong starting with add, because after doing so I print out the arraylist and they show up on the display, but when I try to remove an employee I get my own error message "Employee does not exist" and when I try to find an employee I get the following error message:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    	at java.util.ArrayList.elementData(ArrayList.java:371)
    	at java.util.ArrayList.get(ArrayList.java:384)
    	at Payroll.findAllInfo(Payroll.java:82)
    	at PayrollTest.findEmployee(PayrollTest.java:94)
    	at PayrollTest.main(PayrollTest.java:35)


    In a nutshell, when I add someone and print up the payroll then that person shows up with everyone else, but when I try to remove that person they no longer exist, and then when I try to find anyone, even the ones that were already on the file thats being read in, I get the above error message. I'm at a loss as to what to do, but the problem seems to be stemming from one line, I just can't seem to figure out whats wrong with said line. My code is below, and I've commented the appropiate line I'm referring to.

    import java.io.*;
    import java.util.*;
    public class PayrollTest {
     
        public static void main(String[] args)throws IOException
        {
            Scanner keyboard = new Scanner(System.in);
            Payroll storePayroll = new Payroll("payrollSample1.txt");
            String input;
     
            do {
               System.out.println("Please choose a function below."
                    + "\n\na - add new "
                    + "employee\nr - remove employee from the address book\nf - "
                    + "find an employee's information\np - print out payroll\nq "
                    + "- quit program");
            input = keyboard.nextLine();
     
            if (input.equals("a")) {
                    addEmployee(storePayroll, keyboard);
                }
            else if (input.equals("r")) {
                    removeEmployee(storePayroll, keyboard);
                }
            else if (input.equals("f")) {
                    findEmployee(storePayroll, keyboard);
                }
            else if (input.equals("p")) {
                    storePayroll.printPayRoll();
                }
            }while(!input.equals("q"));
     
     
        }
     
        public static void addEmployee(Payroll storePayroll, Scanner keyboard){
            System.out.println("What is the employee's first name?");
            String firstName = keyboard.nextLine();
     
            System.out.println("What is the employee's last name?");
            String lastName = keyboard.nextLine();
     
            System.out.println("What is the employee's salary?");
            double salary = keyboard.nextDouble();
            keyboard.nextLine();
     
            System.out.println("What is the employee's address?");
            String address = keyboard.nextLine();
     
            boolean success = storePayroll.add(firstName, lastName, salary, address);
     
            if (success == true) {
                System.out.println("The employee has been added.");
            }
            else {
                System.out.println("The employee is already in the system.");
            }
     
        }
     
        public static void removeEmployee(Payroll storePayroll, Scanner keyboard){
            System.out.println("What is the employee's first name?");
            String firstName = keyboard.nextLine();
     
            System.out.println("What is the employee's last name?");
            String lastName = keyboard.nextLine();
     
            boolean success = storePayroll.remove(firstName, lastName);
     
            if (success == true) {
                System.out.println("The employee has been removed.");
            }
            else {
                System.out.println("The employee is not in the system.");
            }
        }
     
        public static void findEmployee(Payroll storePayroll, Scanner keyboard){
            System.out.println("What is the employee's first name?");
            String firstName = keyboard.nextLine();
     
            System.out.println("What is the employee's last name?");
            String lastName = keyboard.nextLine();
     
            System.out.println(storePayroll.findAllInfo(firstName, lastName));
        }
     
     
    }
    import java.io.*;
    import java.util.*;
    public class Payroll {
     
        private ArrayList<Employee> payList;
     
        public Payroll(){
            payList = new ArrayList<>();
        }
     
        public Payroll(String filename)throws IOException{
            payList = new ArrayList<>();
            Scanner fileInput = new Scanner(new File(filename));
            while (fileInput.hasNextLine()){
                String line = fileInput.nextLine();
                //System.out.println("line: " + line);
                StringTokenizer st = new StringTokenizer(line, "~");
                String firstName = st.nextToken();
                String lastName = st.nextToken();
                double salary = Double.parseDouble(st.nextToken());
                String address = st.nextToken();
     
                //String[] tokens = line.split("~");
                //String firstName = tokens[0];
                //System.out.println(firstName);
                //String lastName = tokens[1];
                //System.out.println(lastName);
    	    //double salary = Double.parseDouble(tokens[2]);
                //System.out.println(salary);
    	    //String address = tokens[3];
                //System.out.println(address);
     
                payList.add(new Employee(firstName, lastName, salary, address));
            }
        }
     
        private int search(String firstName, String lastName){
            int i;
            Employee tempEmployee = new Employee(firstName, lastName, 0.0, null);
            for (i = 0; i < payList.size(); i++){
                if (payList.get(i).equals(tempEmployee)) {
                    return i;
                }
            }
            return -1;
        }
     
        public boolean add(String firstName, String lastName, double salary, 
                String address){
            int index = search(firstName, lastName);
            if (index == -1){
                payList.add(new Employee(firstName, lastName, salary, address));
                return true;
            }
            else {
                return false;
            }
        }
     
        public boolean remove(String firstName, String lastName){
            int index = search(firstName, lastName);
            if (index == -1) {
                return false;
            }
            return true;
        }
     
        public String findAllInfo(String firstName, String lastName){
            int index = search(firstName, lastName);
            if (index == -1) {
                System.out.println("The Employee you requested does not work here");
            }
            return payList.get(index).toString();            //****This is the line indicated by the error message****//
        }
     
        public void printPayRoll(){
            int i;
            for (i = 0; i < payList.size(); i++){
            System.out.println(payList.get(i));
        }
        }
     
     
    }
    public class Employee {
     
        static int empcount = 0;
        private int empID = 0;
        private String firstName = null;
        private String lastName = null;
        private String address = null;
        private double salary = 0.0;
     
        public Employee(){
     
        }
     
        public Employee(String fname, String lname, double sal, String addr){
            firstName = fname;
            lastName = lname;
            address = addr;
            salary = sal;
        }
     
        public int getID(){
            return empID;
        }
     
        public String getFirstName(){
            return firstName;
        }
     
        public String getLastName(){
            return lastName;
        }
     
        public String getAddress(){
            return address;
        }
     
        public double getSalary(){
            return salary;
        }
     
        public void setFirstName(String fname){
            firstName = fname;
        }
     
        public void setLastName(String lname){
            lastName = lname;
        }
     
        public void setAddress(String addr){
            address = addr;
        }
     
        public String toString(){
            return firstName + "~" + lastName + "~" + salary + "~" + address;
        }
     
        public boolean equals (Object obj){
            return false;
        }
     
     
     
    }


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need some help with removing and finding items from an ArrayList

    First, your error message is pretty clear about what is happening, you are trying to access an element of an array out of the range of the array.
    For example if you have an array from zero to n, then any index less than zero or greater than n would be out of bounds.

    Now look at the method which includes your comment about the error:
     public String findAllInfo(String firstName, String lastName){
            int index = search(firstName, lastName);
            if (index == -1) {
                System.out.println("The Employee you requested does not work here");
            }
            return payList.get(index).toString();            //****This is the line indicated by the error message****//
        }
    /*Lets step through this method assuming your method index returns the value 3:*/
    if(index == -1)  {}       //which 3 != 1, so this block of code is skipped
    return payList.get(index).toString();        //this returns the toString of the fourth element (located at index 3) of the payList array
     
    /*Now lets step through this method assuming your method index returns the value -1:*/
    if(index == -1) {       //which -1 is equal to -1 so the block runs this time.
    System.out.println("The ....... here");        //this is printed
    }          //The if block ends...
    return payList.get(index).toString();          //This line attempts to return the toString of the -1th element (located out of bounds) of the payList array.

  3. #3
    Member
    Join Date
    Apr 2012
    Posts
    42
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Default Re: Need some help with removing and finding items from an ArrayList

    OK, I see what I did there. Definately a logic error, so I changed it to the code below:

    public String findAllInfo(String firstName, String lastName){
            int index = search(firstName, lastName);
            if (index == -1) {
                System.out.println("The Employee you requested does not work here");
            }
            else {
                return payList.get(index).toString();
            }
            return null;
        }

    And now the error message is gone, but the actual finding of something still doesn't work. After adding a new Employee, that employee still appears on the printout of the entire arraylist, but the program still won't find any employee in the arraylist or remove any employee in the arraylist.

  4. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Need some help with removing and finding items from an ArrayList

    I think that you will want to re-write your Employee equals method. Per your current method, it will always return false:

        public boolean equals (Object obj){
            return false;
        }

    This is not very helpful for your program. Consider adding a line or two of code that will return true when the obj passed into the method should be considered the same as the current Employee object.

    Note how you use this method:

            Employee tempEmployee = new Employee(firstName, lastName, 0.0, null);
            for (i = 0; i < payList.size(); i++){
                if (payList.get(i).equals(tempEmployee)) {
                    return i;
                }
            }
            return -1;

    This should help you figure out what fields of Employee should be used when determining if two Employees should be considered equal. You'll also want to create an override method for public int hashCode() that returns the same int if two Employee objects are equal.
    Last edited by curmudgeon; August 30th, 2012 at 09:21 PM.

  5. #5
    Member
    Join Date
    Apr 2012
    Posts
    42
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Default Re: Need some help with removing and finding items from an ArrayList

    As soon as I posted my last post, I immediantly went straight to that method and completely forgot that I set it to default because I got tired of seeing the error message while I was coding the rest of it. That was the problem, it kept returning false and therefore was never actually true of anything compared with it. I'm glad you noticed it too. I tend to just put defaults whenever I'm not sure about the internals of a method, so thats probably something I'm gonna have to learn to keep track of better from here on out. Thanks for the help again curmudgeon, as well as jps. If anything I'm gonna have to learn to keep track of my methods better. Another learning experience for the day.

  6. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Need some help with removing and finding items from an ArrayList

    As painful as it might seem, this learning experience will pay you dividends in the future when you again need to flex your debugging muscles again. Glad you've got things working. And nice going!

Similar Threads

  1. How do I display 4 items at a time of an ArrayList?
    By JavaStruggler in forum Member Introductions
    Replies: 5
    Last Post: August 9th, 2011, 03:33 PM
  2. Finding String in ArrayList
    By Noob_Programmer in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 6th, 2011, 06:18 AM
  3. Help with Finding Max and Min Values of ArrayList
    By CheekySpoon in forum Collections and Generics
    Replies: 3
    Last Post: March 2nd, 2011, 08:57 PM
  4. Arraylist removing element
    By Stn in forum Loops & Control Statements
    Replies: 6
    Last Post: January 9th, 2011, 08:14 PM
  5. Arrays: question about "removing" items.
    By sanfor in forum Collections and Generics
    Replies: 2
    Last Post: November 30th, 2009, 04:09 AM