Java 为什么它读的是字母的数量而不是单词?
我必须写一个程序,从文本文件中读取输入Java 为什么它读的是字母的数量而不是单词?,java,Java,我必须写一个程序,从文本文件中读取输入 Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch. 我应该打印行数、最长行数、每行上的令牌数以及每行上最长令牌的长度 我试图弄明白为什么我的代码是读字母的数量而不是单词的数量 Line 1 has 5 tokens (longest =
Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch.
我应该打印行数、最长行数、每行上的令牌数以及每行上最长令牌的长度
我试图弄明白为什么我的代码是读字母的数量而不是单词的数量
Line 1 has 5 tokens (longest = 11)
Line 2 has 8 tokens (longest = 6)
Line 3 has 6 tokens (longest = 6)
Line 4 has 3 tokens (longest = 13)
Longest line : the jaws that bite, the claws that catch,
这应该是我的输出
import java.io.*;
import java.util.*;
public class InputStats{
public static void main (String [] args )
throws FileNotFoundException{
Scanner console = new Scanner ( System.in);
System.out.println(" ");
System.out.println();
System.out.println("Please enter a name of a file " );
String name = console.nextLine();
Scanner input = new Scanner ( new File (name));
while (input.hasNextLine()) {
String line = input.nextLine();
inputStats(new Scanner(line));
}
}//end of amin
public static void inputStats (Scanner input)
throws FileNotFoundException{
int numLines=0;
int numwords=0;
int Longest=0;
String maxLine = "";
while (input.hasNextLine()){
String next = input.nextLine();
numwords += next.length();
numLines++;
}//end of while
System.out.print("Line " + numLines + " has ");
System.out.print(numwords + "tokens " );
System.out.println("(longest = " + Longest + ")");
}//end of method
}// end of class
将每行的长度添加到
numwords
计数器变量,而不是每行的字数。而不是
numwords += next.length();
可以根据空格进行拆分
numwords += nextLine.split("\\s+").length;
如果我明白你在找什么像这样的东西应该行得通
public static void inputStats(Scanner input)
throws FileNotFoundException {
int numLines = 0;
int numwords = 0;
String longest = "";
String maxLine = "";
while (input.hasNextLine()) {
String nextLine = input.nextLine();
nextLine = (nextLine != null) ? nextLine
.trim() : "";
if (nextLine.length() > maxLine.length()) {
maxLine = nextLine;
}
StringTokenizer st = new StringTokenizer(
nextLine);
while (st.hasMoreTokens()) {
String token = st.nextToken();
token = (token != null) ? token.trim() : "";
if (token.length() == 0) {
continue;
}
numwords++;
if (token.length() > longest.length()) {
longest = token;
}
}
numLines++;
}// end of while
System.out.print("Line " + numLines + " has ");
System.out.print(numwords + "tokens ");
System.out.println("(longest = " //
+ longest + ")");
}// end of method
如果我试着只数一个单词的字母而不是整行的话,我该如何改变这一点呢。。如果(next.length()>maxLine.length()){maxLine=next;这是给我的字母数,但在这行中不清楚你的意思。我建议发布另一个问题,用该代码解释什么不起作用:)