0

I have a java program below. At first, I tried to get input n as this

int n = sc.nextInt();

But output was different than expected. It runs the first iteration without taking the userName. After changing to

int n = Integer.parseInt(sc.nextLine());

It's working fine. Can someone explain, what was wrong with "int n = sc.nextInt();"

public class StringUserNameChecker {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());   //number of username u want to enter
        while (n-- != 0) {
            String userName = sc.nextLine();
            System.out.println("Your UserName is " + userName);
        }
    }
}

1 Answers1

0

When sc.nextLine() is used after sc.nextInt(), it will read a newline character after the integer input.

So, to run your code correctly, you'll have to use sc.nextLine() after sc.nextInt(), like this:

int n = sc.nextInt();
sc.nextLine();
while(n-- > 0) {
String username = sc.nextLine();
}