java.util.Scanner:仅使用空格输入的行为?
我尝试为Java课程编写一个小型解析器:解析器使用Scanner类:java.util.Scanner:仅使用空格输入的行为?,java,Java,我尝试为Java课程编写一个小型解析器:解析器使用Scanner类: import java.util.Scanner; import java.io.*; public class WC1 { public static void main(String[] args) throws Exception{ File f = new File(args[0]); Scanner in = new Scanner(f); int c=
import java.util.Scanner;
import java.io.*;
public class WC1 {
public static void main(String[] args) throws Exception{
File f = new File(args[0]);
Scanner in = new Scanner(f);
int c=0, w=0, l=0;
while (in.hasNext()) {
String line = in.nextLine();
int N = line.length();
boolean word = false;
for (int i=0;i<N;i++) {
char ch = line.charAt(i);
if (ch == '\r' || ch=='\n') {
if (word == true) w++;
word = false; // do nothing
}
else if (ch == ' ' || ch == '\t') {
if (word == true) w++;
word = false;
c++;
}
else {
word = true;
c++;
}
}
if (word == true) w++;
word = false; // scanner consumes newline but does not return it
c++; // scanner throws away the newline
l++;
System.out.println(line);
}
in.close();
System.out.println("" + c + " characters");
System.out.println("" + w + " words");
System.out.println("" + l + " lines");
}
}
wc File1.dat
779 characters
136 words
3 lines
3 136 779 test.dat
文件2:
cat
dog
goose chicken
rat
dragon
crab
java MyClass文件2.dat
47 characters
7 words
7 lines
7 7 47 File2.dat
wc File2.dat
47 characters
7 words
7 lines
7 7 47 File2.dat
但这不起作用:
文件3:
|
|
|
|
|
|
|
|
java MyClass文件3.dat
0 characters
0 words
0 lines
8 0 36 File3.dat
wc File3.dat
0 characters
0 words
0 lines
8 0 36 File3.dat
文件3仅由空格和换行符组成:管道符号表示行尾
这里发生了什么?注意文件2中的空行。为什么扫描程序似乎忽略了文件3中的空格?扫描程序使用定界符模式将其输入分解为标记,默认情况下,定界符模式与空白相匹配。然后,可以使用各种后续方法将生成的令牌转换为不同类型的值
在这里,您正在检查扫描仪是否正确,但仍在继续。这些基本上是无关的。您发现的结果是,您的第三个文件没有标记(由空格分隔的非空格),但有行。您应该始终使用实际使用的推进方法检查hasXXX
,在您的情况下:
while (in.hasNextLine()) {
String line = in.nextLine();
寻求快速帮助。谁来读这篇文章。你能给出一个摘要或jist你的问题是什么吗?只是想知道:在“文件1:”下,你是故意混淆的吗?该文本是测试文件的全部部分,与您的问题没有特别的相关性,还是其中的某些部分也用于描述您的问题?