我想知道将 Scanner 类与 System.console.readLine() 方法结合使用是否会导致更快的输入读取。举个例子,我使用上述两种方法创建了以下程序,只有 Scanner 类和 System.console.readLine() 方法:
扫描仪和 System.console.readLine():
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.console().readLine());
while (!in.hasNextInt())
in = new Scanner(System.console().readLine());
System.out.println("This is an int: " + in.nextInt());
System.out.println("This is a single char: " + System.console().readLine());
System.out.println("This is a whole String input: " + System.console().readLine());
while (!in.hasNextInt())
in = new Scanner(System.console().readLine());
System.out.println("This is again an int: " + in.nextInt());
}
}
扫描器:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (!in.hasNextInt())
in.next();
System.out.println("This is an int: " + in.nextInt());
System.out.println("This is a single char: " + in.nextLine().charAt(0));
System.out.println("This is a whole String input: " + in.nextLine()); // copy-pasting the "\n" char will break input.
while (!in.hasNextInt())
in.next();
System.out.println("This is again an int: " + in.nextInt());
}
}
安慰:
public class Test {
public static void main(String[] args) {
int input;
while (true) {
try {
input = Integer.parseInt(System.console().readLine());
break;
} catch (IllegalNumberFormat e) {}
}
System.out.println("This is an int: " + input);
System.out.println("This is a single char: " + System.console().readLine().charAt(0));
System.out.println("This is a whole String input: " + System.console().readLine());
while (true) {
try {
input = Integer.parseInt(System.console().readLine());
break;
} catch (IllegalNumberFormat e) {}
}
System.out.println("This is again an int: " + input);
}
}
对于每种类型的大量数据,以上哪一项最快?