0
 System.out.print("Enter name:");
 name=sc.nextLine();

 System.out.print("Enter nric: ");
 nric=sc.nextLine();

 System.out.print("Enter age: ");
 age=sc.nextInt();

 System.out.print("Enter gender(male/female): ");
 gender=sc.nextLine();

 System.out.print("Enter weight:");
 weight=sc.nextInt();

 System.out.print("Enter height: ");
 height=sc.nextDouble();

Well, every time after I enter age, I cannot enter gender. I would really appreciate it if you could help me, thanks.

Madhawa Priyashantha
  • 9,208
  • 7
  • 28
  • 58

3 Answers3

0

nextInt() will stop after reading the int value, it wont go to new line to read values further. you have to add a nextLine() after nextInt() or You can read age as String using nextLine() and later parse it as int using a wrapper class.

0

because Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine so for your program you have to put another nextLine for consuming the nextLine

it will perfect when adding the sc.nextLine after enter age

 System.out.print("Enter name:");
 name=sc.nextLine();

 System.out.print("Enter nric: ");
 nric=sc.nextLine();

 System.out.print("Enter age: ");
 age=sc.nextInt();
 sc.nextLine();// for consuming the nextLine

 System.out.print("Enter gender(male/female): ");
 gender=sc.nextLine();

 System.out.print("Enter weight:");
 weight=sc.nextInt();

 System.out.print("Enter height: ");
 height=sc.nextDouble();
jitendra varshney
  • 3,262
  • 1
  • 17
  • 25
0

Simply use this before taking input of a line of a string.

sc= new Scanner(System.in);

Your code:

 System.out.print("Enter name:");
 name=sc.nextLine();

 System.out.print("Enter nric: ");
 sc= new Scanner(System.in);
 nric=sc.nextLine();

 System.out.print("Enter age: ");
 age=sc.nextInt();

 System.out.print("Enter gender(male/female): ");
 sc= new Scanner(System.in);
 gender=sc.nextLine();

 System.out.print("Enter weight:");
 weight=sc.nextInt();

 System.out.print("Enter height: ");
 height=sc.nextDouble();

When you invoke nextLine(), the line is removed from the buffer and effectively discarded from the Scanner.

Md. Nasir Uddin Bhuiyan
  • 1,568
  • 1
  • 13
  • 22