繁体   English   中英

计数行字字符和filenotfound异常java eclipse。

[英]Counting lines words characters and filenotfound exception java eclipse.

// 问题是行和单词一直说 0。 不过,它正在正确计算字符。 而且我真的不确定如何添加 FileNotFoundException 。 我的老师甚至没有教我们班这个。 我班上的每个人都在挣扎:(

 import java.util.*;
 import java.io.*;

public class FileReader
{  
public static void main(String[]args) throws FileNotFoundException        
{ 
        Scanner console = new Scanner(System.in);           

        System.out.println("File to be read: ");
        String inputFile = console.next();

        File file = new File(inputFile);
        Scanner in = new Scanner(file);

        int words = 0;
        int lines = 0;
        int chars = 0;

        in = new Scanner(file);
        while(in.hasNext())
        {
            in.next();
            chars++;
        }
        in = new Scanner(file);
        while(in.hasNextLine())
        {
            in.nextLine();
            lines++;
        }
        in = new Scanner(file);
        while(in.hasNextByte())
        {
            in.nextByte();
            words++;
        }

        System.out.println("Number of lines: " + lines);
        System.out.println("Number of characters: " + chars);
        System.out.println("Number of words: " + words);
}
}

总是尝试捕获异常而不是抛出异常。 将整个主代码放在 try 块中,并在 catch 块中捕获所有异常。 java中的异常处理很容易。 一个关于 try catch 的小教程可以帮助你更多。

您收到 FileNotFoundException 是因为您没有指定文件的完整路径。 File f = new File(complete/path/of/file);

console.next() 只会给你输入到控制台的文本,而不是整个路径。

我建议您使用完整路径创建一个字符串并将其提供给 File()。

我认为这个解释对你的家庭作业来说太过分了;)

希望这可以帮助。

在第一个 while 循环中,您实际上是在计算单词数,但将其分配给字符。 字符数可以很容易地从这个循环中每个单词的长度中计算出来。

import java.util.*;
import java.io.*;

public class FileReader {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner console = new Scanner(System.in);

        System.out.println("File to be read: ");
        String inputFile = console.next();

        File file = new File(inputFile);
        Scanner in = new Scanner(file);

        int words = 0;
        int lines = 0;
        int chars = 0;

        in = new Scanner(file);
        while (in.hasNext()) {
            chars += in.next().length();
            words++;
        }
        in = new Scanner(file);
        while (in.hasNextLine()) {
            in.nextLine();
            lines++;
        }

        /*
         * in = new Scanner(file); while(in.hasNextByte()) { in.nextByte();
         * words++; }
         */

        System.out.println("Number of lines: " + lines);
        System.out.println("Number of characters: " + chars);
        System.out.println("Number of words: " + words);
    }
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM