java


Remove element of arraylist from user input without using iteratior


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
Simple problem: instead of passing a Friends Object to the remove() method, you pass just the String. Write a custom remove code.
Also keep in mind to always do indexed deleting from bottom to top to not jump entries:
System.out.print("Enter Friend's name to remove: ");
name = input.next();
// friendsList.remove(name);
System.out.println("Trying to locate <" + name + ">");
for (int i = friendsList.size() - 1; i >= 0; --i) {
final Friends f = friendsList.get(i);
System.out.println("\tChecking with <" + friendsList.get(i).name + ">");
if (f.name.equals(name)) {
System.out.println("Found that bitch at index " + i);
friendsList.remove(i);
System.out.println("... and kicked him out");
}
}
break;
A simple mechanism to use is removeIf. Something like:
friendsList.removeIf(friend -> friend.hasName(name);
Note this uses Java 8.
That is assuming a hasName method of Friend. If you only have getName then:
friendsList.removeIf(friend -> friend.getName().equals(name));

Related Links

modifiers for multiple objects in java
Java String validation using enum values and annotation
JAVA Read Integers form a Text File and Work on the Array Lists
customize application with xml java
getParent for jframe that is attribute of a JPanel
Inserting Items to BoxLayout at Runtime?
Using ext-js with java /spring
How to use the accelerometer to detect virbration above or equal to 2Gs?
Flyway migration during ear deployment
User/Role/Module based architecture
Java ternary operator and setting loop index values
Java BufferedOutputStream strategy
How to mock a method call on the constructor using easymock?
Get android notification from app?
design pattern to handle version specific display to user
Formatting Specific Parts of a Listview Item

Categories

HOME
gitlab
asp.net-core
deployment
webpack
amazon-ec2
keycloak
google-play
tinymce
layout
iterator
kalman-filter
at-command
cross-browser
ebean
onelogin
constraint-programming
upload
append
slick-slider
communication
tomcat6
fancybox-3
offline
modx-revolution
export-to-csv
etl
gz
worldwind
saxon
finite-automata
undefined
plunker
visjs
physics-engine
sox
core-text
bootstrap-tour
hammerspoon
crystal-reports-2010
jaxb2
ecto
avcapturesession
xmlreader
mmenu
picasso
leading-zero
elmah
firebase-admin
nxlog
password-encryption
flashair
businessworks
segment
avconv
strptime
winscp-net
colorama
knpmenubundle
arrow-keys
webdriverjs
objective-c-swift-bridge
messenger
xcb
trash
clang-static-analyzer
connect-by
lttng
ford-fulkerson
srand
reactive-banana
qtableview
execute
prerequisites
lib.web.mvc
icu4j
metaclass
purge
twirl
cisco-ios
oberon
key-management
block-device
rake-task
tt-news
cdt
rdtsc
project-planning
heisenbug
aapt
navigationservice
inbox
odata4j
quartz-graphics
qt-faststart
sqlperformance
mqx
limejs
cassini-dev
pvrtc
isnullorempty
broken-links
word-processor
javaspaces
uiviewanimation-curve
eclipse-templates
nsobject
hirefire
hamachi
netbeans-7.1
imac
google-friend-connect
forums
data-driven
privilege
zend-decorators
data-acquisition
windows-live-messenger
document-conversion

Resources

Encrypt Message