I have a doubt in java Constructor

import java.util.Scanner;
class Emp
{
int eid;
String ename;
Emp(int id, String name)
{
eid =id;
ename = name;
}
}
public class Prime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
String name = sc.nextLine();

     Emp navin = new Emp(id,name);
     System.out.println(navin.eid);
     System.out.println(navin.ename);          
}

}

//it only gets one scanner input int not the string value
//or is this correct approach or not

Please format the code
Three backticks (```) before the code and after the code :slight_smile:
As for your question , I don’t know if I am understanding it right but
try to add

sc.nextLine() ;

After you take the integer (id) input

2 Likes

thanks for the answer
but i have already added the sc.nextline to get the string

nextInt() doesn’t read new line, i.e., it ignores the newline character. So, whenever we try to accept a String value after the integer value, the nextLine() considers the new line provided, as string and terminates. Some solutions are:

  1. accept String value before integer value.
  2. write one more ‘sc.nextLine()’ after the nextInt(), i.e,
    int id=sc.nextLine();
    sc.nextLine();
    String name = sc.nextLine();
    Hope this helps.
3 Likes

thanks I did as you said now it works.