假设我输入以下内容:
3
24 1
4358 754
305 794
当我尝试如下阅读时,它不起作用:
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
{
sc.nextLine();
int a = sc.nextInt();
int b = sc.nextInt();
//DoSomethingWithAandB
}
我这样做是因为首先我要跳过第一行。然后我读了两个整数。之后,如果还有另一行,请使用sc.nextLine()转到该行,然后再次读取整数。怎么了?
答案 0 :(得分:3)
在上面的输入中,第一行应该是行数,因此,一旦阅读,就可以进行循环,然后读取并分割行,以得到数字。
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
}
如果您不需要阅读第一行,则可以与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
}
答案 1 :(得分:2)
第一行中的3表示您需要阅读多少行,因此您应该使用该信息,而不是仅依靠 hasNextLine() ,后者不会使用提供的所有信息给你:
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();
}
}
}
输出:
A: 24, B: 1
A: 4358, B: 754
A: 305, B: 794
input.txt:
3
24 1
4358 754
305 794
如果您确实想在while循环中使用 hasNextLine() ,则需要在while循环之外跳过第一行和3:
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();
}
}
}