有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java平均字长。文本

我找不到文本文件的平均字长。由于某种原因,我得到的输出是0。这个程序还可以找到文本文件中的总字数,我已经记下了,只是找不到平均字长

public class WordCount {
    public static void main(String[] args) throws FileNotFoundException {
        while (true) {
        System.out.println("Enter File name: ");
        Scanner input=new Scanner (System.in);
        String fileName= input.nextLine();
        FileReader wordReader;
        File file = new File("text.txt");
        try {
            wordReader=new FileReader(fileName);
            BufferedReader reader=new BufferedReader(wordReader);
            String wordCounter;
            int numberWords=0;
            double avgWord=0;
            double chara=0;


            while((wordCounter=reader.readLine()) !=null) {
                String []words=wordCounter.split(" ");

                for(int i=0;i<words.length;i++)
                {
                    numberWords++;
                }
            }
                while((wordCounter=reader.readLine()) !=null) {
                String []charWords=wordCounter.split("");
                for (int j=0;j<charWords.length;j++) {
                    chara++;
                }
                avgWord=chara/numberWords;


            }






            System.out.println("Total words: "+ numberWords);
            System.out.println("Average word length: "+ avgWord);
            }catch (FileNotFoundException ex) {
            System.out.println("File not found");
            System.out.println("Example of a valid input: /Users/Marcus/Documents/text.txt");

        } catch (IOException e) {
            e.printStackTrace();
        }
        }




    }
}

共 (1) 个答案

  1. # 1 楼答案

    第二个while循环将立即返回,因为reader已耗尽

    while((wordCounter=reader.readLine()) !=null) {
    

    您必须首先创建一个新的reader