Why does this scanner only read my first input? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why does this scanner only read my first input?

This is the code: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = 0; System.out.print("enter number of rows: "); int rows = sc.nextInt(); while (x <= rows) { String name = sc.nextLine(); System.out.print("Enter Name: " + name); char gender = sc.next().charAt(0); System.out.println("Gender (M | F): "+gender); So whenever i input in name example is john i always get the fist letter on the char which is j. Can somebody explain to me how does this scanner works and why i always get the first letter of name when i try to input in gender? Sorry for my english though. This is not my first language

6th Feb 2022, 1:51 AM
Easy Carry
1 Answer
+ 8
The concept that you've used in your code is right, but the problem happens with the "sc.nextInt()" statement. When you enter something to the input(buffer), it is stored with a terminating '\n' character(cuz we press enter at the end). For example if you enter 45 and press enter key, the input buffer has the data "45\n". The function nextInt() takes the integer 45 and leaves the '\n' in the buffer. So your buffer now has "\n" in it. After this, you enter your name and now the buffer holds "\njohn". Now, the nextLine() function thinks it's a empty string and takes \n and stores it in the string name and leaves "john" in the buffer. Now the line "sc.next().charAt(0)" takes the first letter j and stores it in gender and thus you get this problem. Now let's see how to solve this. To solve this, just remove the '\n' from the buffer manually after the nextInt() function call. You can do this by adding the line "sc.nextInt()" after the nextInt() call line
6th Feb 2022, 2:43 AM
Rishi
Rishi - avatar