简体   繁体   English

有人可以帮我弄清楚我的 WhiteSpaceCounter 代码有什么问题吗?

[英]Can someone help me figure out what is wrong with my WhiteSpaceCounter code?

I need a program that counts the whitespace in a text document, but it keeps giving me an insane number of whitespaces, as I think the while loop just keeps repeating.我需要一个程序来计算文本文档中的空格,但它总是给我大量的空格,因为我认为 while 循环只是不断重复。 could anyone read it over and tell me what is up?任何人都可以阅读并告诉我发生了什么事吗?

import java.io.*;
public class WhiteSpaceCounter {
    public static void main(String[] args) throws IOException {
        File file = new File("excerpt.txt");
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader inreader = new InputStreamReader(fis);
        BufferedReader reader = new BufferedReader(inreader);
        String sentence;
        int countWords = 0, whitespaceCount = 0;
        while((sentence = reader.readLine()) != null) {
            String[] wordlist = sentence.split("\\s+");
            countWords += wordlist.length;
            whitespaceCount += countWords -1;
        }
        System.out.println("The total number of whitespaces in the file is: "
                            + whitespaceCount);
}

} }

If you first line has 3 word and your second line has 10 words, then you logic is如果您的第一行有 3 个单词,而您的第二行有 10 个单词,那么您的逻辑是

countWords (0) += 3 -> 3

countWords(3) += 10 -> 13

So do not use +=所以不要使用 +=

countWords = wordlist.length;

You could also use this你也可以用这个

    while((sentence = reader.readLine()) != null) {
        String[] wordlist = sentence.split("\\s+");
        whitespaceCount += wordlist.length-1;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人可以帮我找出导致PlayFair Cipher出现错误异常的原因吗? - Can someone help me figure out what may be causing error exceptions in my PlayFair Cipher? 有人可以找出我的代码有什么问题吗? - Can someone figure out whats wrong with my code? 起初它说我的输出代码不可用,现在它说存在错误。 有人可以帮我弄清楚我的错误在哪里吗? - At first it said my output code was unreachable now it says there is an error. Can someone help me figure out where my error is? 有人可以找出此TableLayout的问题吗? - Can someone figure out what is wrong with this TableLayout? 有人可以帮我弄清楚写这个while循环吗? - Can someone help me figure out to write this while loop? 有人可以帮我弄清楚为什么我不能调用我的方法吗? - Can someone help me figure out why i cant call my method? 有人可以帮我弄清楚如何从“:”(不包括)读取我的文件直到行尾? - Can someone help me to figure out how to read my file from ":" (not included) til the end of the line? 有人可以帮我弄清楚为什么我的一种方法根本没有运行吗? - Can someone help me figure out why one of my methods is not running at all? 有人可以帮我解决这个问题吗? 关于unicode - can someone help me to figure this out ? about unicode 无法弄清楚我的合并排序代码有什么问题 - Can't figure out what is wrong with my merge sort code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM