据我所知,在Java中从文件中读取基于字符的数据的两种最常见的方法是使用Scanner或BufferedReader。我还知道BufferedReader通过使用缓冲区来避免物理磁盘操作,从而有效地读取文件。
我的问题是:
扫描器的性能和BufferedReader一样好吗? 为什么你会选择扫描器而不是BufferedReader,反之亦然?
据我所知,在Java中从文件中读取基于字符的数据的两种最常见的方法是使用Scanner或BufferedReader。我还知道BufferedReader通过使用缓冲区来避免物理磁盘操作,从而有效地读取文件。
我的问题是:
扫描器的性能和BufferedReader一样好吗? 为什么你会选择扫描器而不是BufferedReader,反之亦然?
我使用扫描器方法nextInt()和nextLine()读取输入。
它是这样的:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
问题是在输入数值之后,第一个input.nextLine()被跳过,第二个input.nextLine()被执行,因此我的输出看起来像这样:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
我测试了我的应用程序,看起来问题在于使用input.nextInt()。如果我删除它,那么string1 = input.nextLine()和string2 = input.nextLine()都按照我想要的方式执行。