0

I am writing a program for which students going to the cashier of particular department or faculty are given a token number which is automatically generated and they line up in a queue to wait for their turn to enter. The program should allow the user to insert a new student in the queue by adding his name and token number into the system among its other features.

I don't know how to add a new student to the queue.

Here is what I have come up so far:

Student class

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;
    }

}

Main class

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*/
      }



    }


}
0

2 Answers 2

2

You should write:

stdtQ.add(new Student(sc.hasNext(), sc.nextInt()));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It should be stdtQ.add(new Student(sc.next(), sc.nextInt())); though
1

Queues typically order elements in a FIFO manner. So if you are interested in using the token number to sort the queue you should check priority queues.

By calling the add method you are already adding new elements to the stdtQ queue. If you want toadd other students to that queue you fist have to create the object ( by getting the values from the input for example) and the add it with the add method.

You can print all the student in the queue like this:

for(Student s : stdtQ){
    System.out.println(s.getName() + s.getTnum());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.