我必须编写一个从文本文件中读取输入的程序!
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发布于 2014-03-16 08:53:48
您将每行的长度添加到numwords计数器变量,而不是每行的字数。而不是
numwords += next.length();您可以根据空格进行拆分
numwords += nextLine.split("\\s+").length;发布于 2014-03-16 08:54:50
如果我知道你在找什么,这样的东西应该行得通,
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 methodhttps://stackoverflow.com/questions/22431621
复制相似问题