gpt4 book ai didi

java - 计算文件中的字符、单词和行数

转载 作者:行者123 更新时间:2023-12-01 18:44:45 26 4
gpt4 key购买 nike

这应该计算文件中的行数、单词数和字符数。

但是这不起作用。从输出中仅显示 0

代码:

public static void main(String[] args) throws IOException {
int ch;
boolean prev = true;
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;

Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}

// count the characters of the file till the end
while(in.hasNext()) {
ch = in.next().charAt(0);
if (ch != ' ') ++charsCount;
if (!prev && ch == ' ') ++wordsCount;
// don't count if previous char is space
if (ch == ' ')
prev = true;
else
prev = false;

if (ch == '\n') ++linesCount;
}

//display the count of characters, words, and lines
charsCount -= linesCount * 2;
wordsCount += linesCount;
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);

in.close();
}

我不明白发生了什么事。有什么建议吗?

最佳答案

不同的方法。使用字符串查找行数、单词数和字符数:

public static void main(String[] args) throws IOException {
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;

Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}

while (in.hasNext()) {
String tmpStr = in.nextLine();
if (!tmpStr.equalsIgnoreCase("")) {
String replaceAll = tmpStr.replaceAll("\\s+", "");
charsCount += replaceAll.length();
wordsCount += tmpStr.split(" ").length;
}
++linesCount;
}

//display the count of characters, words, and lines
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);

in.close();
}

<小时/> 注意:
对于其他编码样式,请使用 new Scanner(new File(selectedFile), "###"); 代替 new Scanner(selectedFile);

### 是所需的字符集。请参阅thiswiki

关于java - 计算文件中的字符、单词和行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18274391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com