'Why i am getting the exception for nextLine() and not for next() while takin string inputs

Recently I have started programming and I don't know how to handle an exception that I am receiving while taking string input for op.nextLine(). However the code is working for op.next() Why it might be giving me such exceptions?

import java.util.*;
import java.util.Scanner;
import java.io.*;

public class Employee_Class_object {
        
  // Fields
  private int emp_no;
  private String na; 
  private double salary;

  // method 
  public void getData()
  {
    Scanner op = new Scanner(System.in);
    System.out.println("Enter the emoployee no , Name and salary ");
    emp_no = op.nextInt();
    na  = op.nextLine(); // Showing exception for nextLine() and not for op.next()

    salary = op.nextDouble();
  }

  public void putData()
  {
    System.out.println("Employee no = " + emp_no);
    System.out.println("Employee name = " + na);
    System.out.println("Employee Salary  = " + salary);
  }

  public static void main (String args[])
  {
    Employee_Class_object a = new Employee_Class_object();
    Employee_Class_object  b = new Employee_Class_object();
    a.getData();
    a.putData();
  }
}


Solution 1:[1]

The possible reason of the exception is that you're still reading the first line (after reading emp_no at 4th line of your getData() method). Before you read the next line, move the reader to next line. Something like this:

public void getData()
  {
    Scanner op = new Scanner(System.in);
    System.out.println("Enter the emoployee no , Name and salary ");
    emp_no = op.nextInt();//after reading this, you're still at the same line.
    op.nextLine();// Now you are on the NEXT line.
    na  = op.nextLine();

    salary = op.nextDouble();
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1