我想从arraylist中添加,更新和删除元素。由于我是Java新手或任何类型的编程,我无法在谷歌搜索后找出整个解决方案。我可以添加元素到arrayList。以下是我的代码:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Student> someStudent = new ArrayList<Student>();
char quit = 'Y';
int id;
String name;
float cgpa;
while(quit == 'Y'){
System.out.print("\n ID: ");
id=scan.nextInt();
System.out.print("\n Name: ");
name=scan.next();
System.out.print("\n CGPA: ");
cgpa=scan.nextFloat();
someStudent.add (new Student(id, name, cgpa));
System.out.print(" Enter Another Record? (Y/N)");
String word = scan.next();
word = word.toUpperCase();
quit= word.charAt(0);
//scan.close();
}
for(Student student:someStudent){
System.out.println(student.id);
System.out.println(student.name);
System.out.println(student.cgpa);
}
}
}
Student.java:
public class Student {
public int id;
public String name;
public float cgpa;
//public String address;
public Student(int id,String name,float cgpa){
this.id=id;
this.name=name;
this.cgpa=cgpa;
}
}
代码输出:
ID: 1
Name: abc
CGPA: 3.5
Enter Another Record? (Y/N)y
ID: 2
Name: def
CGPA: 2.6
Enter Another Record? (Y/N)y
ID: 3
Name: xyz
CGPA: 4.0
Enter Another Record? (Y/N)n
1
abc
3.5
2
def
2.6
3
xyz
4.0
我的问题是如何从该arraylist中搜索元素并更新或删除它们。
答案 0 :(得分:1)
您可以尝试这样的事情:
System.out.print("Select student by ID: ";
int pickID = scan.nextInt();
boolean found = false;
for(Student s : someStudent){
if(s.id == pickID && !found){
update(s);
found = true;
}
}
if(!found){
System.out.println("No student with that ID.");
}
更新方法
public void update(Student s){
boolean edit = true;
while(edit){
System.out.println(String.format("Select operation:\n1. Change name\n2. Change ID\n3. Change CGPA\n4. Delete\n5. Done"));
int opt = scan.nextInt();
switch(opt){
case 1:
String newName = scan.next();
s.setName(newName);
break;
case 2:
int newID = scan.nextInt();
s.setID(newID);
break;
case 3:
float newCGPA = scan.nextFloat();
s.setCGPA(newCGPA);
break;
case 4:
for(int i=0;i<someStudent.length();i++){
if(someStudent.get(i)==s){
someStudent.remove(i);
}
}
break;
case 5:
edit = false;
break;
default:
break;
}
}
}
向Student class
添加方法public void setID(int id){this.id=id;}
public void setName(String name){this.name=name;}
public void setCGPA(float cgpa){this.cgpa=cgpa;}
答案 1 :(得分:0)
根据您想要搜索的内容(我猜名称不是唯一的,ID是cgpa怎么样?)您应该使用Map而不是列表。因此,您将能够根据该地图中的唯一键找到学生。