import java.io.*;public class TextStatistics { private String inputFileName; private String outputFileName; private int numChars; private int numWords; public TextStatistics(String inputFile, String outputFile) { inputFileName = inputFile; outputFileName = outputFile; numChars = 0; numWords = 0; } public void count() { try { BufferedReader reader = new BufferedReader(new FileReader(inputFileName)); String line; while ((line = reader.readLine()) != null) { numChars += line.length(); String[] words = line.split(" "); numWords += words.length; } reader.close(); } catch (IOException e) { e.printStackTrace(); } } public void output(boolean toFile) { String output = "Number of characters: " + numChars + "\n"; output += "Number of words: " + numWords + "\n"; if (toFile) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName)); writer.write(output); writer.close(); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println(output); } }}public class TextStatisticsTest { public static void main(String[] args) { System.out.println("Welcome to Text Statistics!"); System.out.println("Please enter the name of the input file: "); Scanner scanner = new Scanner(System.in); String inputFile = scanner.nextLine(); System.out.println("Please enter the name of the output file: "); String outputFile = scanner.nextLine(); System.out.println("Do you want to output to a file? (Y/N)"); boolean toFile = scanner.nextLine().equalsIgnoreCase("Y"); TextStatistics stats = new TextStatistics(inputFile, outputFile); stats.count(); stats.output(toFile); }}
时间: 2024-02-15 13:30:52 浏览: 144
import java.net.*;import java.io.*;
5星 · 资源好评率100%
这段代码是用 Java 编写的一个文本统计程序,可以统计输入文件中的字符数和单词数,并将结果输出到控制台或输出文件中。程序包括两个类,TextStatistics 类和 TextStatisticsTest 类。TextStatistics 类用于实现文本统计功能,其中 count() 方法用于统计字符数和单词数,output() 方法用于输出结果到控制台或输出文件中。TextStatisticsTest 类用于测试 TextStatistics 类的功能,其中通过控制台输入输入文件名、输出文件名和是否输出到文件的选项,并调用 TextStatistics 类的方法进行统计和输出。
阅读全文