我正在練習編寫一個程序,該程序從用戶獲取文本文件,並在文本中提供數據(如字符,單詞和行)。用於計算文本給定文件中的行數,字數和字符數的Java程序
我已經搜索並查看了相同的主題,但無法找到使代碼運行的方法。
public class Document{
private Scanner sc;
// Sets users input to a file name
public Document(String documentName) throws FileNotFoundException {
File inputFile = new File(documentName);
try {
sc = new Scanner(inputFile);
} catch (IOException exception) {
System.out.println("File does not exists");
}
}
public int getChar() {
int Char= 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
Char += line.length() + 1;
}
return Char;
}
// Gets the number of words in a text
public int getWords() {
int Words = 0;
while (sc.hasNext()) {
String line = sc.next();
Words += new StringTokenizer(line, " ,").countTokens();
}
return Words;
}
public int getLines() {
int Lines= 0;
while (sc.hasNextLine()) {
Lines++;
}
return Lines;
}
}
主要方法:
public class Main {
public static void main(String[] args) throws FileNotFoundException {
DocStats doc = new DocStats("someText.txt");
// outputs 1451, should be 1450
System.out.println("Number of characters: "
+ doc.getChar());
// outputs 0, should be 257
System.out.println("Number of words: " + doc.getWords());
// outputs 0, should be 49
System.out.println("Number of lines: " + doc.getLines());
}
}
我知道爲什麼我得到的1451,而不是1451的原因是因爲我沒有「\ n」在最後一句,但我的方法結束添加 numChars + = line.length()+ 1;
但是,我無法找到一個解決方案,爲什麼我得到0的單詞和行。 *我的文本包含以下元素:? , - '
畢竟,有人能幫我做這個工作嗎?
**到目前爲止,我關心的問題是如何得到一些字符,如果最後一句沒有'\ n'元素。有沒有機會我可以用if語句解決這個問題?
- 謝謝!
請顯示您的實際代碼。你正在調用一個方法getNumberOfCharacters,它不存在於你的代碼中,所以這甚至不會編譯,更不用說運行 – Stultuske
另外:不要使用StringTokenizer。這是一個遺留類,不應該使用。使用字符串的拆分方法或正則表達式。新的StringTokenizer(行,「,」)這分裂在一個「,」,所以:「我在這裏」你不會真的包含單詞。 – Stultuske
這是我的實際代碼。我稱之爲不同方法的原因是因爲我運行了很多類似的代碼,以瞭解如何修復我自己的代碼。這就是爲什麼我忘記將它改回我的方法的原因。 –