The topic requirement is to read in such data
3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
Seeing such a format, I thought of using the nextLine() method to read by line, the format is as follows
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String[] scores = new String[num];
for (int i = 0; i < num; i++) {
scores[i] = sc.nextLine();
}
for (String score : scores) {
System.out.println(score);
}
However, using this method will miss the last line every time, and subsequent operations will lead to out-of-bounds
. After consulting the data, I got some gains:
1. All the data we read in are first stored in the buffer
2.Scanner is actually read from the bufferSpace, characters separated by \t,\n,\r
3. After the buffer reads the first integer, \r is left, and \n is the separator of next(), so it is equivalent to wasting the first nextline() of our loop
#### Improve the way to add a nextLine() to clear the buffer after reading the integer
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String[] scores = new String[num];
sc.nextLine();
for (int i = 0; i < num; i++) {
scores[i] = sc.nextLine();
}
for (String score : scores) {
System.out.println(score);
}
This will solve the problem