只是想說這個程序幾乎在任何方面都擊敗了我。 輸入什麼我需要做的是一個.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