Java Scanner nextLine Issue, additional enter is needed
Clash Royale CLAN TAG#URR8PPP
Java Scanner nextLine Issue, additional enter is needed
I'm studying java I/O. There is some issue on my code.
I want to print
[0, 0, 1]
[1, 0, 1]
[0, 0, 1]
[2, 0, 1]
[10, 0, 5]
But additional enter is needed.
public static void main(String args)
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
sc.nextLine();
System.out.println();
for (int i = 0; i < tc; i++)
int line = sc.nextInt();
sc.nextLine();
for (int j = 0; j < line; j++)
System.out.println(i+""+j);
int st = Arrays.stream(sc.nextLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(st));
Below is input & output. And I don't know why [10, 0, 5] is not shown. If I push enter key, then [10, 0, 5] appears.
Input
2
2
0 0 1
1 0 1
3
0 0 1
2 0 1
10 0 5
Output
[0, 0, 1]
[1, 0, 1]
[0, 0, 1]
[2, 0, 1]
(additional enter)
[10, 0, 5]
tc
@ernest_k not true. If you don't have it, the
nextLine
call immediately following a nextInt
will return an empty string.– Andy Turner
Aug 6 at 8:01
nextLine
nextInt
@intentionallyleftblank sorry, tc means test case. 2 at the top is tc.
– user4235523
Aug 6 at 8:01
So you want to 1) ask the user for the number of test cases, then 2) you collect these, each being an integer. Then what? What is the idea in words?
– user9455968
Aug 6 at 8:03
@user4235523 I cannot reproduce this behavior.
– Andy Turner
Aug 6 at 8:29
2 Answers
2
read the java doc for nextLine
method.
nextLine
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
This nextLine call blocks until it finds line seperator, which is the additional enter.
int st = Arrays.stream(sc.nextLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
Thx! I thought all examples include line seperator. But some of them include line seperator, the others not. I figured it out now.
– user4235523
Aug 7 at 9:19
//your code is working as expected for given input after removing some print statements
public static void main(String args)
Scanner sc = new Scanner(Paths.get(System.in));
int tc = sc.nextInt();
sc.nextLine();
//remove extra print statement
// System.out.println();
for (int i = 0; i < tc; i++)
int line = sc.nextInt();
sc.nextLine();
for (int j = 0; j < line; j++)
//remove extra print statement
// System.out.println(i+""+j);
int st = Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(st));
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Can you explain the idea behind this code? What does
tc
mean?– user9455968
Aug 6 at 7:58