Suppose I have the following input:
3
24 1
4358 754
305 794
When I try to read it as follows it doesn't work:
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
{
sc.nextLine();
int a = sc.nextInt();
int b = sc.nextInt();
//DoSomethingWithAandB
}
I do it that way because first I want to skip the first line. Then I read the two integers. After that if there is another line I go to it with sc.nextLine() and I read the integers again. What is wrong?
In the input above, the first line is supposed to be the number of lines, so once you read it, you can do a loop then read the line and split it so you get your numbers.
Scanner in = new Scanner(System.in);
int numberOfLines = in.nextInt();
for (int i = 0; i < numberOfLines; ++i) {
String line = in.nextLine();
String[] lineSplit = line.split(" ");
int a = Integer.parseInt(lineSplit[0]);
int b = Integer.parseInt(lineSplit[1]);
//DoSomethingWithAandB
}
If you don't need to read the first line, you can use while with in.hasNextLine()
Scanner in = new Scanner(System.in);
in.nextInt();
while (in.hasNextLine()) {
String line = in.nextLine();
String[] lineSplit = line.split(" ");
int a = Integer.parseInt(lineSplit[0]);
int b = Integer.parseInt(lineSplit[1]);
//DoSomethingWithAandB
}
The 3 on the first line indicates how many lines you need to read, so you should use that information rather than only relying on hasNextLine() , which is not using all the information provided to you:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class FileInputExample {
public static void main(String[] args) {
File file = new File("input.txt");
try {
Scanner scanner = new Scanner(file);
int n = scanner.nextInt(); // This reads the 3 in your example
for (int line = 1; line <= n; line++) {
int a = scanner.nextInt();
int b = scanner.nextInt();
// Do something with a and b like store them in ArrayLists or something
System.out.println(String.format("A: %d, B: %d", a, b));
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
A: 24, B: 1
A: 4358, B: 754
A: 305, B: 794
input.txt:
3
24 1
4358 754
305 794
If you do want to use hasNextLine() in a while loop, you need to skip the first line with the 3, outside the while loop:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class FileInputExample {
public static void main(String[] args) {
File file = new File("input.txt");
try {
Scanner scanner = new Scanner(file);
scanner.nextLine(); // skip the 3 on the first line
while (scanner.hasNextLine()) {
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(String.format("A: %d, B: %d", a, b));
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.