I need to remove any element of ArrayList, from user input and without using java iterator:
(see (switch) case 2:)
when I select Option 2 and proceed to input a name, for example James, it wont do anything as the list of friends would be the same. Any help would be much appreciated!
import java.util.Scanner;
import java.util.ArrayList;
public class FriendsTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// objects
ArrayList<Friends> friendsList = new ArrayList<>();
Friends a1 = new Friends("James", 10);
Friends a2 = new Friends("Christopher", 17);
Friends a3 = new Friends("George", 25);
Friends a4 = new Friends("Linda", 31);
Friends a5 = new Friends("Karen", 62);
friendsList.add(a1);
friendsList.add(a2);
friendsList.add(a3);
friendsList.add(a4);
friendsList.add(a5);
// menu
int menu_choice;
String name;
int age;
do
{
System.out.println("\n1. Add a Friend");
System.out.println("2. Remove a Friend");
System.out.println("3. Display all Friends");
System.out.println("4. Exit\n");
System.out.print("\nSelect one option: ");
menu_choice = input.nextInt();
switch (menu_choice)
{
case 1:
System.out.print("Enter Friend's name: ");
name = input.next();
System.out.print("Enter Friend's age: ");
age = input.nextInt();
Friends a6 = new Friends(name, age);
friendsList.add(a6);
break;
case 2:
System.out.print("Enter Friend's name to remove: ");
name = input.next();
friendsList.remove(name);
break;
case 3:
for(int k = 0; k < friendsList.size(); k++)
{
System.out.println(friendsList.get(k).name + " " + friendsList.get(k).age);
}
break;
case 4:
System.exit(0);
}//end switch
} while (menu_choice != 4);
}//end main
}//end class
Update with my constructor and methods class
public class Friends
{
public String name;
public int age;
// parameters
public Friends(String _name, int _age)
{
name = _name;
age = _age;
}
// set name
public void setName(String friendName)
{
name = friendName;
}
// get name
public String getName()
{
return name;
}
// set age
public void setAge(int friendAge)
{
age = friendAge;
}
// get age
public int getAge()
{
return age;
}
// return toString()
public String toString()
{
return getName() + " " + getAge();
}
} //end clas
Friendswill need to override (and correctly implement) theequalsandhashcodemethods. You should then be able to useArrayList#remove(T)to remove and element by creating a newFriendsobject with the EXACT same properties as the one you have in youListStringfrom anArrayListofFriends.