英文:
Remove User from list of users in java
问题
我对Java还不熟悉,所以请原谅我的解释可能不够清楚,但我有一个列表:
private LinkedList<User> users = new LinkedList<User>();
还有一个名为removeUser的方法:
private void removeUser() {
System.out.println("All Users: ");
viewUsers();
System.out.print("Please enter the ID of the user to be removed: ");
int choice = In.nextInt();
for (User user : users) {
if (users.contains(choice)) {
users.remove(choice);
}
}
}
现在当我运行代码时,它成功地打印出了所有内容。但是当我检查列表内容时,什么也没有改变,我不确定我在代码的移除部分做错了什么。
英文:
I'm new to java, so please excuse me if my explanation is poor but I have a list :
private LinkedList<User> users= new LinkedList<User>();
and a method removeUser:
private void removeUser() {
System.out.println("All Users: ");
viewUsers();
System.out.print("Please enter the ID of the user to be removed: ");
int choice = In.nextInt();
for (User user : users){
if (users.contains(choice)) {
users.remove(choice);
}
}
}
Now when I run the code it successfully prints out everything. Yet when I check the list contents, nothing has changed and I'm unsure of what I have done wrong with the removal part of the code.
答案1
得分: 1
另一种解决方案:如果你想使用 lambda 表达式和流来移除具有对应 ID 的第一个用户。
private void removeUser() {
System.out.println("所有用户:");
viewUsers();
System.out.print("请输入要移除的用户的 ID:");
int choice = In.nextInt();
users.stream()
.filter(user -> user.getId() == choice)
.findFirst()
.ifPresent(users::remove);
}
英文:
Alternative solution: if you want to use lambda and streams to remove first User with corresponding ID.
private void removeUser() {
System.out.println("All Users: ");
viewUsers();
System.out.print("Please enter the ID of the user to be removed: ");
int choice = In.nextInt();
users.stream()
.filter(user->user.getId() == choice)
.findFirst()
.ifPresent(users::remove);
}
答案2
得分: -1
如果您想从列表中移除某个项目,您不能使用 for-each 循环。参考:https://stackoverflow.com/questions/33582050/what-is-a-difference-between-traditional-loop-and-for-each-loop
我认为您需要相同的操作:
private void removeUser() {
System.out.println("所有用户:");
viewUsers();
System.out.print("请输入要移除的用户的 ID:");
int choice = In.nextInt();
for (int i = 0; i < users.size(); i++){
User user = users.get(i);
if (user.contains(choice)) {
users.remove(i); // 在索引 i 处移除
}
}
}
希望能帮到您!
英文:
If you want remove some item from list you can't use for-each loop. Refer: https://stackoverflow.com/questions/33582050/what-is-a-difference-between-traditional-loop-and-for-each-loop
I think you need same:
private void removeUser() {
System.out.println("All Users: ");
viewUsers();
System.out.print("Please enter the ID of the user to be removed: ");
int choice = In.nextInt();
for (int i = 0; i < users.size(); i++){
User user = users.get(i);
if (user.contains(choice)) {
users.remove(i); // remove at index i
}
}
}
Hope can help you!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论