こんにちは私はこのプログラムに問題があります。学生情報をタイプStudent
のオブジェクトに格納する必要があります。保存情報:ラストネーム、グレード、および投票。投票はArrayList
のInteger
に格納されています。 Student
という新しいオブジェクトを作成するたびにStudent
というタイプのArrayList
に追加すると(それは学校のすべての生徒を保存します)、既に入力した前のStudent
オブジェクトに入力した新しい投票を追加し続けますArrayList
に格納されます。オブジェクトにArrayListを渡す
例:私は学生ArrayList
にStudent
を追加し、私は入力フレディ、5b及び123に与え、その後、私は学生ArrayList
をチェックし、それは私がすでに追加されている学生含まれています:フレディ、5b及び123を、私は別のものを追加します私は入力ジョシュ、4tと1234を与える私はチェック
ArrayList
で既に作成され、格納されているオブジェクトを変更しますか?どうすれば修正できますか?ここで
はコードです:
public class Student {
private String lastname;
private String grade; // example "4b"
private ArrayList<Integer> student_votes;
public Student(String lastname, String grade, ArrayList<Integer> student_votes) {
this.lastname=lastname;
this.grade=grade;
this.student_votes=student_votes;
}
public ArrayList getVotes() {
return student_votes;
}
public String getLastname() {
return lastname;
}
public String getGrade() {
return grade;
}
public String toString() {
return lastname+" "+grade+" "+getVotes();
}
public void print_student (Student student) {
System.out.println(student);
}
public static void print_students(ArrayList<Student> students) {
for(Student s : students) {
System.out.print(s);
}
System.out.println("");
}
public static void menu() {
System.out.println("\nPress 1 to add a student\nPress 2 to remove a student\nPress 3 to print the classroom\nPress 4 to exit");
}
public static void main(String[] args) {
int choice, nv=0, i=0,average=0;
Boolean exit=false;
ArrayList<Student> students = new ArrayList<Student>();
ArrayList<Integer> votes = new ArrayList<Integer>();
String lastname = new String();
String grade = new String();
Scanner sc = new Scanner(System.in);
Scanner st = new Scanner(System.in);
do {
menu();
choice=sc.nextInt();
switch (choice) {
case 1: System.out.println("Enter your lastname:");
lastname=st.nextLine();
System.out.println("Enter your grade:");
grade=st.nextLine();
System.out.println("Enter the amount of votes");
nv=sc.nextInt();
for(i=0;i<nv;i++) {
System.out.println("Enter vote n:"+(i+1));
votes.add(sc.nextInt());
}
students.add(new Student(lastname,grade,votes));
System.out.println("student added!");
break;
case 2: System.out.println("Enter student position: ");
nv = sc.nextInt();
students.remove(nv-1);
break;
case 3: print_students(students);
break;
case 4: exit = true;
}
} while (exit==false);
}
}
なぜ2つのスキャナがありますか?あなたは1つしか使用できず、同じ目標を達成することができます。 –
同じリストオブジェクトをすべての生徒に設定しています。異なる内容が必要な場合は、別のものを構築する必要があります。 – shmosel
@shmoselだから私はすべての学生のためのarraylistを作成する必要がありますか?それを避ける方法はありますか? – BlueJay