有 Java 编程相关的问题?

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

java我正在尝试从文件中计算字符数

我在这里要做的是读取一个文件并计算每个字符。每个字符应在“int count”上加+1,然后打印出“int count”的值

我希望我要做的是清楚的

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

public class ScanXan {

public static void main(String[] args) throws IOException {

    int count = 0;
    Scanner scan = null;
    Scanner cCount = null;

    try {
        scan = new Scanner(new BufferedReader(new FileReader("greeting")));

        while (scan.hasNextLine()) {
            System.out.println(scan.nextLine());
        }
    }

    finally {
        if (scan != null) {
            scan.close();
        }
    }

    try {

        cCount = new Scanner(new BufferedReader(new  FileReader("greeting")));
        while (cCount.hasNext("")) {
            count++;
        }
    }

    finally {
        if (cCount != null) {
            scan.close();
        }
    }

    System.out.println(count);

}

}

共 (4) 个答案

  1. # 1 楼答案

    1. 添加catch块以检查异常
    2. 从hasNext(“”)中删除参数
    3. 移动到下一个令牌

          cCount = new Scanner(new BufferedReader(new  FileReader("greeting")));
          while (cCount.hasNext()) {
                  count = count + (cCount.next()).length();
          }
      
  2. # 2 楼答案

    首先,为什么要使用try { }而不使用catch(Exception e)

    BufferedReader reader = null;
    try {
    reader = new BufferedReader(new    FileReader("greetings.txt"));
    String line = null;
    String text = "";
    while ((line = reader.readLine()) != null) {
         text += line;
    }
    int c = 0; //count of any character except whitespaces
     // or you can use what @Alex wrote
     // c = text.replaceAll("\\s+", "").length();    
    for (int i = 0; i < text.length(); i++) {
        if (!Character.isWhitespace(text.charAt(i))) {
            c++;
        }
    }
    System.out.println("Number of characters: " +c);
    } catch (IOException e) {
         System.out.println("File Not Found");
    } finally {
         if (reader != null) { reader.close();
         }
    }
    
  3. # 3 楼答案

    如果你在寻找一种只计算所有字符和整数的方法,而不需要任何空格,比如“tab”、“enter”等等。。然后,您可以首先使用以下函数删除这些空白:

    st.replaceAll("\\s+","")
    

    然后你只需要做一个字符串计数

    String str = "a string";
    int length = str.length( );
    
  4. # 4 楼答案

    使用Java8流API,您可以按如下方式进行

    package example;
    
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class CountCharacter {
    
        private static int count=0;
    
        public static void main(String[] args) throws IOException {
            Path path = Paths.get("greeting");
            try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
                count = lines.collect(Collectors.summingInt(String::length));
            }
            System.out.println("The number of charachters is "+count);
        }
    
    }