java - 计算文本文件中的数字和单词程序

标签 java input

我需要编写一个简单的程序来计算文本文件中的单词数并给出数字总数。该程序必须计算所有数字的总和和平均值。平均值是总和除以计数。文件将数字和单词一起计数。它只打印 34。

//CAT DOG BIRD FISH
//1 2 3 4 5
//TURTLE LIZARD SNAKE
//6 7 8 9 10
//FISH SHARK
//11 12 13 14 15
//SPIDER FLY GRASSHOPPER ANT SCORPION
//16 17 18 19 20


import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JOptionPane;

public class HomeWork8 {

    public static void main(String[] args) throws IOException {
        String words, numbers, message;
        int numberWords = 0, countNumber = 0;
        FileInputStream fis = new FileInputStream("/Users/ME/Documents/Words and Numbers.txt");
        Scanner in = new Scanner(fis);

        while (in.hasNext()) {
            words = in.next();

            numberWords++;

        }

        while (in.hasNext()) {
            in.useDelimiter("");
            numbers = in.next();
            countNumber++;
        }

        in.close();

        message = "The number of words read from the file was " + numberWords
                + "\nThe count of numbers read from the file was" + countNumber;
        JOptionPane.showMessageDialog(null, message);
    }
}

最佳答案

String pattern ="\\d";
        String word="shdhdshk 46788 jikdjsk 9 dsd s90 dsds76";
        Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(word);
        int count=0;
        while (m.find()) {            
            count++;
        }
        System.out.println(count);

如果您需要获取单个数字字符数,可以使用 \d 。但是如果您对整数出现感兴趣,那么您必须使用 \d+ 而不是 \d。例如:46788,9,90,76

关于java - 计算文本文件中的数字和单词程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33704686/

相关文章:

输入范围 - 实时发送值

python - Python 2.x 和 3.x 中输入命令的区别

java - IntelliJ IDE | .iml 文件丢失或删除

java - 解析具有奇怪语法的 XML 文件

javascript - 如果我在之前的选择中选择了一个选项,则删除输入字段

python - 使用 python xlib 全局捕获、忽略和发送键事件,识别虚假输入

jquery - 动画文本输入高度

java - 如何在 SWT 中添加处理 PApplet

java - 使用 Eclipse 从 eBay 沙盒 WSDL 创建 stub 时出错

java - 探索pdf中的水平解析TJ(对tx公式的详细了解)?