我这里有一个程序,它应该读入文件并计算文件中文本的密度,然后在图表中显示结果。到目前为止,它在输入文本时起作用,但是当我试图将其设置为读取文件时我收到了缓冲读取器的错误(我在错误的行上放了*)而且我在分析文件名时分析文件中的文本时遇到了问题。
非常感谢任何帮助
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
public class assignment
{
static boolean drawn = false;
static final int num = 4;
BufferedReader bf = null;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("please enter a file name");
String filename = in.nextLine();
*bf = new BufferedReader(new FileReader(filename));*
String[] data = {filename};
diagram(data);
in.close();
}
public static void diagram(String[] lines)
{
Map<Character, Integer> words = new HashMap<Character, Integer>();
for(String l : lines)
{
for(String w : l.split("\\s+"))
for(char c : w.trim().toCharArray())
if(words.containsKey(c))
words.put(c, words.get(c) + 1);
else
words.put(c, 1);
}
//first the most occuring then the printing
words.forEach(new BiConsumer<Character, Integer>(){
int i;
@Override
public void accept(Character t, Integer u)
{
if(u > i){
i = u;
rdraw(words, i);
}
}
});
}
private static void rdraw(Map<Character, Integer> words, final int l)
{
if(drawn)
return;
words.forEach(new BiConsumer<Character, Integer>(){
@Override
public void accept(Character t, Integer u)
{
System.out.print(t + ": ");
double d = (u * num)/l;
for(int i = 0; i < (int)d; i++)
System.out.print("=");
System.out.println();
}
});
drawn = true;
}
}
答案 0 :(得分:0)
如果您想阅读文件,请按以下步骤操作:
Scanner in = new Scanner(System.in);
System.out.println("please enter a file name");
String filename = in.nextLine();
in.close();
File file = new File(filename);
ArrayList<String> list = new ArrayList(); // Cant use a regular array because the length is unknown.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
现在你有一个arraylist,它应该包含文件中的所有行,你可以使用它。