I want to avoid the issue of "new line character" that is generated by pressing the enter key when I enter a number for nextInt()
, since nextLine()
will consume the new line character and won't let me input the string.
I am using a custom Delimiter to avoid this issue so that nextInt()
can consume the end of line character as well
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
sc.useDelimiter("\\n");
System.out.println("Enter your age");
int age=sc.nextInt();
System.out.println("Enter your name");
String name=sc.nextLine();
System.out.println("Age is "+ age);
System.out.println("Name is "+ name);
}
}
However when I run this program I get this error :
Enter your age
4
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Test.main(Test.java:8)
I can't understand why I am getting an InputMismatchException. Can someone explain how this delimiter works?
As pointed by @Abra in comments, if I use next()
instead of nextLine()
it works as intended. The question is why does nextLine()
doesn't work?