我想知道如果将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);
}
}
对于每种类型的大量数据,上述哪一项最快?