+ 1
How can I capture the "\n" at then end to one value scanned by the user in Java
scanner scan = new scanner (system.in); int l= scan.nextInt(); char t = scan.nextLine().charAt(0); and then the character t take the "\n" after the digitation of int. I wanna ask how can i resolve this problem to take real first Character.
2 Réponses
+ 4
Remove the first char at the string str[0]
Then after removing str[0] is a real char
+ 2
You can just make a nextLine() call after the nextInt() call and before the nextLine() in which you actually accept input. This will take in up to the '\n' char left behind by the call to nextInt().
Scanner scan = new Scanner (System.in);
int i = scan.nextInt();
scan.nextLine();
char t = scan.nextLine().charAt(0);
Or you can just use nextLine() to get your int as well and convert it to an int
Scanner scan = new Scanner (System.in);
int i = Integer.parseInt(scan.nextLine());
char t = scan.nextLine().charAt(0);