gpt4 book ai didi

java.util.Scanner : Behavior with whitespace-only input?

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:38 25 4
gpt4 key购买 nike

我尝试为 Java 类(class)编写一个小型解析器:该解析器使用 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=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");
}

}

文件1:

我使用下面的三个小输入文件对其进行了测试:

The reason for the exception is that you are calling keyIn.close() after you use the scanner once, which not only closes the Scanner but also System.in. The very next iteration you create a new Scanner which promptly blows up because System.in is now closed. To fix that, what you should do is only create a scanner once before you enter the while loop, and skip the close() call entirely since you don't want to close System.in.

After fixing that the program still won't work because of the == and != string comparisons you do. When comparing strings in Java you must use equals() to compare the string contents. When you use == and != you are comparing the object references, so these comparisons will always return false in your code. Always use equals() to compare strings.

java MyClass File1.dat

779 characters
136 words
3 lines

wc File1.dat

3     136     779 test.dat

文件2:

cat
dog
goose chicken
rat
dragon

crab

java MyClass File2.dat

47 characters
7 words
7 lines

wc File2.dat

7     7     47 File2.dat

但这不起作用:

文件3:

       |
|
|
|
|
|
|
|

java MyClass File3.dat

0 characters
0 words
0 lines

wc File3.dat

8     0     36 File3.dat

文件 3 仅由空格和换行符组成:管道符号表示行尾。

这里发生了什么?注意 File2 中的空行。为什么扫描程序似乎忽略了 File3 中的空格?

最佳答案

while (in.hasNext()) {
String line = in.nextLine();

您在这里检查扫描仪 hasNext但继续前进nextLine 。这些基本上是不相关的。您发现的结果是您的第三个文件没有标记(由空格分隔的非空格),但它有行。在您的情况下,您应该始终检查 hasXXX 与您实际使用的升级方法:

while (in.hasNextLine()) {
String line = in.nextLine();

关于java.util.Scanner : Behavior with whitespace-only input?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22999317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com