我正在寫一個程序,讓學生去某個部門或教職員的收銀員獲得一個自動生成的令牌號碼,並排隊等候輪到他們進入。該程序應允許用戶通過將他的姓名和令牌編號添加到系統中的其他功能中來插入新的學生。Java:如何使用參數添加或創建新對象並將其添加到隊列中?
我不知道如何將新學生添加到隊列中。
這裏是我想出迄今:
Student類
package queues;
import java.util.Random;
public class Student {
private String name;
private int tnum;
public Student(String name, int tnum){
this.name=name;
this.tnum=tnum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTnum() {
return tnum;
}
public void setTnum(int tnum) {
this.tnum = tnum;
}
public String toString(){
return "Student name: "+ name+ " Token num: "+tnum;
}
}
主類
package queues;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
public class Student_Main{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int opt;
Student stdt= new Student("Sophia", 1);
Student stdt2= new Student("Amelia", 2);
Student stdt3= new Student("Karxlina", 4);
Student stdt4= new Student("Rachel", 3);
Queue<Student> stdtQ= new LinkedList<Student>();
stdtQ.add(stdt);
stdtQ.add(stdt2);
stdtQ.add(stdt3);
stdtQ.add(stdt4);
System.out.println(stdtQ);
System.out.println("Please choose an option. ");
System.out.println("To insert new student, enter 1.");
opt= sc.nextInt();
if(opt==1){
stdtQ.add(Student(sc.hasNext(), sc.nextInt())); /*this doesn't work of course*/
}
}
}
謝謝!它應該是'stdtQ.add(new Student(sc.next(),sc.nextInt()));'儘管 – Tia