只是想说这个程序几乎在任何方面都击败了我。 输入什么我需要做的是一个.txt文件,其中包含此在文本文件中计数单词?
应该有 59个字符 13个字 和 6号线在此文件 。
不知道如何将其格式化为6行。
则计算该行,但说,有78个字的文本文件,而不是13这是6 * 13 = 78
我怎样才能得到它的只读行一次..因此阅读13个字不是13 * 6。该程序似乎在计算多次的单词。 (评论是由proffesor指导)。
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
String name;
int lineCount = 0;
int wordCount = 0;
System.out.println("Please type the file you want to read in: ");
name = s.nextLine();
// create a Scanner object to read the actual text file
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\" + name + ".txt");
Scanner in = new Scanner(input);
while (in.hasNextLine()){ // enter while loop if there is a complete line available
// increase line counter variable
lineCount++;
// read in next line using Scanner object, inFile
in.nextLine();
// create another Scanner object in order to scan the line word by word
Scanner word = new Scanner(input);
// use while loop to scan individual words, increase word counter
while(word.hasNext()){
// increase word counter
wordCount++;
// Scanner move to next word
word.next();
}
word.close();
// count number of chars including space but not line break by using the length() method of the String class and increment character counter
}
in.close();
System.out.print("Lines " + lineCount + " "+ "Words " + wordCount);
}
我想用'两个扫描仪'输入'是造成问题。你可以这样做:接受。字符串oneline = in.nextLine。 – frunkad 2015-02-11 19:31:03
您需要将字词扫描仪移至线路扫描器的while循环之外。正如您现在所拥有的,您正在声明扫描仪这个词并扫描文件中每一行的整个文件。 – mstbaum 2015-02-11 19:31:29
@mstbaum你是我的救世主。我想要血淋淋地抓住我的头发。 – 2015-02-11 19:33:23