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