我必须将txt文件复制到RAM(使用ByteArrayOutputStream),然后列出包含所有单词和重复次数的列表。 但是,当我尝试打印该列表时,它会打印我
“java.util.Scanner中[定界符= \ p {javaWhitespace} +] [位置= 0] [匹配 valid = false] [need input = false] [来源 closed = false] [skipped = false] [group separator = \] [decimal separator = \,] [positive prefix =] [negative prefix = \ Q- \ E] [positive suffix =] [negative suffix =] [NaN string = \ Q?\ E] [infinity string = \ Q?\ E]
我发现这里的问题在哪里(扫描仪不是字符串对象)但找不到解决方案。
您可以查看我的代码并提供帮助吗? {
public class JavaRam {
File f;
byte [] bTab;
Scanner sc;
String tempLine;
ByteArrayOutputStream baos;
StringTokenizer st;
long startTime=0;
long stopTime=0;
HashMap<String,Integer> hm;
JavaRam(String fileName) throws IOException{
startTime=System.currentTimeMillis();
loadFile(fileName); //load file to ram
System.out.println("Czas ladowania pliku: "+ (stopTime=System.currentTimeMillis()-startTime));
startTime=System.currentTimeMillis();
hm=new HashMap<String, Integer>();
makeList();
System.out.println("Czas tworzenia listy wyrazow: "+ (stopTime=System.currentTimeMillis()-startTime));
startTime=System.currentTimeMillis();
printing();
System.out.println("Czas drukowania listy wyrazow: "+ (stopTime=System.currentTimeMillis()-startTime));
exit();
System.exit(0);
}
void loadFile(String fileName){
try{
f=new File(fileName+".txt");
sc=new Scanner(f);
}
catch(Exception e){
e.printStackTrace();
}
tempLine=new String(sc.toString());
bTab=tempLine.getBytes();
baos=new ByteArrayOutputStream();
try{
baos.write(bTab);
}
catch(Exception e){
e.printStackTrace();
}
}
void makeList(){
st=new StringTokenizer(baos.toString());
Integer ti; //temporary int
for(String nt=st.nextToken(); st.hasMoreTokens()==true;nt=st.nextToken()){
if(hm.containsKey(nt)==false){
hm.put(nt, 1);
}
else{
hm.put(nt,(Integer)hm.get(nt)+1);
}
}
}
void printing(){
String sl="Slowo";
String lp="Liczba powtorzen:";
String sl1="";
String lp1="";
for(String str:hm.keySet()){
sl1=sl+str;
lp1=lp+hm.get(str).toString();
System.out.printf("\n %-20s, %-20s",sl1,lp1);
}
}
int exit() throws IOException{
baos.close();
sc.close();
return 1;
}
public static void main(String []args){
try {
JavaRam a=new JavaRam("JPJMMWKM");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
提前致谢;)
答案 0 :(得分:2)
tempLine=new String(sc.toString());
似乎错了;你可能想要sc.nextLine()
。
无论如何,你的代码真的很混乱。构造函数中的代码应该是另一个方法,太多实例成员等等。