String name is not getting printed

Viewed 111
import java.util.*;

//student class
class Student{
    String name;
    int rollNo;
    
    Student(String name, int rollNo){
        this.name=new String(name);
        this.rollNo=rollNo;
    }
    

}
class Demo {
    public static void main (String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        int noOfStudents = in.nextInt();
        Student[] StudentList= new Student[noOfStudents];
        PriorityQueue<Student> set=new PriorityQueue<Student>(new Comparator<Student>(){
            public int compare(Student a, Student b){
                return b.rollNo-a.rollNo;
            }
        });
        for(int i=0;i<noOfStudents;i++){
            String name = in.nextLine();
            in.nextLine();
            int rollNo = in.nextInt();
            set.add(new Student(name,rollNo));
        }
        
        while(!set.isEmpty()){
            Student tmp = set.poll();
            System.out.println(tmp.name+" "+tmp.rollNo);
        }   
        
    }
}

test case

I am trying to take n students name and roll no and then printing it. But this is not printing the names of student

I have added the extra nextline() to enable integer entry

I always feel difficulty in this thing. Please help!

3 Answers

Change:

String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();

to

String name = in.next();
int rollNo = in.nextInt();

I think this version works as you can see from the picture. I added this line:

in.nextLine(); // it consumes the newline and moves to the starting of the next line.

Here's the code:

import java.util.*;

//student class
class Student{
    String name;
    int rollNo;

    Student(String name, int rollNo){
        this.name=new String(name);
        this.rollNo=rollNo;
    }  
}
public class Main {
    public static void main (String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Inert the number of students, please");
        int noOfStudents = in.nextInt();
        Student[] StudentList= new Student[noOfStudents];
        PriorityQueue<Student> set=new PriorityQueue<Student>(new Comparator<Student>(){
            public int compare(Student a, Student b){
                return b.rollNo-a.rollNo;
            }
       });
  
       for(int i=0;i<noOfStudents;i++){
           in.nextLine(); // it  consumes the newline and moves to the starting of the next line.
           System.out.println("Enter the student's name "+i);
           String name = in.nextLine();
           System.out.println("Enter the student ID number "+i);
           int rollNo = in.nextInt();
           set.add(new Student(name,rollNo));
       }
    
       while(!set.isEmpty()){
           Student tmp = set.poll();
           System.out.println(tmp.name.toString()+" "+tmp.rollNo);
       }   
    
   }
 }

Execution of Java program

Best regards from Italy.

Related