我正在做这个问题。我提交了以下使用扫描仪读取输入的代码。
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
class Main{
public static void main(String[] args)throws java.lang.Exception{
Scanner cin = new Scanner(System.in);
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
int trees = 0;
while(true){
String tree = cin.nextLine();
if(tree==null){
break;
}
trees++;
if(map.containsKey(tree)){
map.put(tree, map.get(tree)+1);
}else{
map.put(tree, 1);
}
}
for(String key : map.keySet()){
}
Iterator<String> itr = map.keySet().iterator();
while(itr.hasNext()){
String tree = itr.next();
System.out.print(tree + " " );
double percent = (double)map.get(tree)/trees*100;
System.out.format("%.4f\n", percent);
}
}
}
但我得到一个运行时错误。但是当我提交相同的代码但这次我使用缓冲阅读器时,我的答案就会被接受。这是法官的问题还是我错过了java的输入输出例程的某些功能。
我应该使用缓冲阅读器还是扫描仪来更稳健地读取数据?
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
class Main{
public static void main(String[] args)throws java.lang.Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
int trees = 0;
while(true){
String tree = br.readLine();
if(tree==null){
break;
}
trees++;
if(map.containsKey(tree)){
map.put(tree, map.get(tree)+1);
}else{
map.put(tree, 1);
}
}
for(String key : map.keySet()){
}
Iterator<String> itr = map.keySet().iterator();
while(itr.hasNext()){
String tree = itr.next();
System.out.print(tree + " " );
double percent = (double)map.get(tree)/trees*100;
System.out.format("%.4f\n", percent);
}
}
}