使用 Scanner next() 时计算文件中的行数
Count # of lines in a file when using Scanner next()
对于将文本文件字典解析为二次探测哈希的拼写检查程序 table,我在计算行号时遇到问题...
input = new Scanner(userInput);
int counter = 1;
while (input.hasNext())
{
String x = input.next();
x = x.replaceAll("[^a-zA-Z\s]", "").replaceAll("\s+", " ");
if (!dictionary.contains(x))
{
System.out.println("Mispelled word: " + x + ", on line #: " + counter);
}
if (x.contains("\n"))
counter++;
}
这可以正确识别构造为 userInput 的文件中任何位置的拼写错误的单词,但不会生成准确的行号。
由于输入文本文件每行包含多个单词,因此我使用了 input.next() 方法而不是 input.nextLine()。我正在尝试使用 int 计数器来计算正确的行号。
文本文件包含:
This is a missspelled word test documentt.
How many dogs can fly? It doesn't produce correct linee numbbers.
Do you think this really works?
生成行号错误的输出:
Mispelled word: missspelled, on line #: 1
Mispelled word: documentt, on line #: 1
Mispelled word: linee, on line #: 1
Mispelled word: numbbers, on line #: 1
我的带有 counter++ 的 if 语句没有起作用。
这应该有效!
Scanner inputLine;
Scanner inputToken;
try {
int counter = 1;
inputLine = new Scanner(new File("a.txt"));
while(inputLine.hasNextLine()){
inputToken=new Scanner(inputLine.nextLine());
while (inputToken.hasNext())
{
String x = inputToken.next();
x = x.replaceAll("[^a-zA-Z\s]", "").replaceAll("\s+", " ");
if (!dictionary.contains(x))
{
System.out.println("Mispelled word: " + x + ", on line #: " + counter);
}
if (x.contains("\n"))
counter++;
}
counter++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
对于将文本文件字典解析为二次探测哈希的拼写检查程序 table,我在计算行号时遇到问题...
input = new Scanner(userInput);
int counter = 1;
while (input.hasNext())
{
String x = input.next();
x = x.replaceAll("[^a-zA-Z\s]", "").replaceAll("\s+", " ");
if (!dictionary.contains(x))
{
System.out.println("Mispelled word: " + x + ", on line #: " + counter);
}
if (x.contains("\n"))
counter++;
}
这可以正确识别构造为 userInput 的文件中任何位置的拼写错误的单词,但不会生成准确的行号。
由于输入文本文件每行包含多个单词,因此我使用了 input.next() 方法而不是 input.nextLine()。我正在尝试使用 int 计数器来计算正确的行号。
文本文件包含:
This is a missspelled word test documentt.
How many dogs can fly? It doesn't produce correct linee numbbers.
Do you think this really works?
生成行号错误的输出:
Mispelled word: missspelled, on line #: 1
Mispelled word: documentt, on line #: 1
Mispelled word: linee, on line #: 1
Mispelled word: numbbers, on line #: 1
我的带有 counter++ 的 if 语句没有起作用。
这应该有效!
Scanner inputLine;
Scanner inputToken;
try {
int counter = 1;
inputLine = new Scanner(new File("a.txt"));
while(inputLine.hasNextLine()){
inputToken=new Scanner(inputLine.nextLine());
while (inputToken.hasNext())
{
String x = inputToken.next();
x = x.replaceAll("[^a-zA-Z\s]", "").replaceAll("\s+", " ");
if (!dictionary.contains(x))
{
System.out.println("Mispelled word: " + x + ", on line #: " + counter);
}
if (x.contains("\n"))
counter++;
}
counter++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}