-1
    HashMap <Integer, String> students = new HashMap<>();
    Scanner scanner = new Scanner(System.in);
    Integer newStudent;

    do{
        System.out.print("Enter an ID: ");
        newStudent = scanner.nextInt();

        if(!(newStudent == 0)){
            System.out.print("Name: ");
            String name = scanner.nextLine();
            students.put(newStudent, name);
            scanner.nextLine();
        }
    }while (!(newStudent == 0));

    System.out.println("Class Roster: ");

    for(Map.Entry <Integer, String> student : students.entrySet()){
        System.out.println(student.getKey() + " (" + student.getValue() + ")");
    }

It's not printing the name on the console. It just prints "1 ()" and "2()" on console. What I am doing wrong here? Thanks

  • 1
    Your first `nextLine()` gets a blank line (see dupe), and the second one gets the name you input, but you don't capture its value. – khelwood Jun 13 '20 at 01:52

1 Answers1

-1

Change if statement like this.

    if(!(newStudent == 0)){
        scanner.nextLine();    // skip ID line.
        System.out.print("Name: ");
        String name = scanner.nextLine();
        students.put(newStudent, name);
    }
saka1029
  • 13,523
  • 2
  • 13
  • 37