I am having problem to read inputs from console as stated below:
Input:
The first line of input consists number of the test cases. The description of T test cases is as follows:
The first line of each test case contains the size of the array, the second line has the elements of the array and the third line consists of the difference k.
Example:
Input:
2
5
1 5 4 1 2
0
3
1 5 3
2
Here is my code and its incorrect output:
Scanner input = new Scanner(System.in);
int T;
T = input.nextInt();
int[] k_holder = new int[T];
int[] n_holder = new int[T];
int[][] array = new int[T][10000];
for (int i=0; i<T; i++) { // length of test
n_holder[i] = input.nextInt();
String tmp[] = input.next().split(" ");
for (int j=0;j<tmp.length; j++) {
array[i][j] = Integer.parseInt(tmp[j]);
}
int K = input.nextInt(); // difference
k_holder[i] = K;
}
System.out.println("===============");
for (int i=0; i<T; i++) {
System.out.println(n_holder[i]);
for (int j=0; j<n_holder[i]; j++) {
System.out.print(array[i][j] + " ");
}
System.out.print("\n" + k_holder[i]);
}
Output:
2
5
1 5 4 1 2
===============
5
1 0 0 0 0
54
1 0 0 0
2
As soon as I type enter after array_line (in above case array_line is 1 5 4 1 2), I got strange output
As you didn't provide your expected result. It is hard to tell what exactly you are going to do, the following are my suggestions.
add
input.nextLine();
after all yournextInt()
statements,nextInt()
cannot consume the newline character(\n), therefore it needsinput.nextLine()
capture it, or the result will messed up.use
String tmp[] = input.nextLine().split(" ");
to parse your space separated line,next()
only handles the first token.import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDateTime; import java.util.Scanner;
My test:
You didn't actually ask a question here, but if you're wondering why your array output is 1 0 0 0 0 instead of 1 5 4 1 2, the reason is because you call
instead of
Note that scanner is whitespace delimited by default. This means that
input.next()
only grabs the first token until it hits whitespace. So if your input "1 5 4 1 2", it's only grabbing the 1, and then doing some funky scanner slurp with the rest of the input. I believe it's even grabbing the rest of that line as the next inputs to scanner! So yourinput.nextInt()
somehow ropes in 54, then loop back up,input.next()
grabs 1, and the finalinput.nextInt()
grabs 2 (hence the funny output, and observe we can sort of see 1 5 4 1 2 running down the side).Why it decided that the nextInt() was 54 instead of 5 is not clear to me, though.