程序说明:
I have this program of mine which is intended to read every word from a file (large one) and then check if the words already exist in a word-array which keeps the unique words or not. If not, add the word to the end of the array, and add +1 to a uniquewordcounter as well as to a counting array at the same index.. If the word already is located somewhere in the array, it should locate the index-number, and on the same index-number in a counting-array increase the value with 1. This it should do while the file has more content. I am not allowed to use HashMaps either.
然而,当我的程序要读取文件时,它会进入无限的 while 循环,并且唯一单词的计数眨眼间就轻松超过 100.000,但它最多应该为 5000...
这是代码:
class Oblig3A{
public static void main(String[]args){
OrdAnalyse oa = new OrdAnalyse();
String filArgs=args[0];
oa.analyseMetode(filArgs);
}
}
class OrdAnalyse{
void analyseMetode(String filArgs){
//Begins with naming all of the needed variables
Scanner input, innfil;
String[] ord, fortelling;
int[] antall;
int antUnikeOrd, totalSum;
PrintWriter utfil;
//Declaring most of them.
input=new Scanner(System.in);
ord=new String[5000];
antall=new int[5000];
antUnikeOrd=0;
totalSum=0;
try{
innfil=new Scanner(new File(filArgs));
//The problem is located here somewhere:
while(innfil.hasNext()){
fortelling=innfil.nextLine().toLowerCase().split(" ");
ord[0]=innfil.next().toLowerCase();
for(int i=0; i<fortelling.length; i++){
for(int j=0; j<5000; j++){
if(fortelling[i].equals(ord[j])){
antall[j]+=1;
System.out.print("heo");
}else{
ord[j]=fortelling[i];
antall[j]+=1;
antUnikeOrd+=1;
}
System.out.println(ord.length);
System.out.println(antUnikeOrd);
}
}
}
innfil.close();
}catch(Exception e){
e.printStackTrace();
}
// Here the program will write all the info acquired above into a file called Oppsummering.txt, which it will make.
try{
utfil=new PrintWriter(new File("Oppsummering.txt"));
for(int i=0; i<antall.length; i++){
totalSum+=antall[i];
}
utfil.println("Antall ord lest: " +totalSum+ " og antall unike ord: "+antUnikeOrd);
for(int i=0; i<ord.length; i++){
utfil.println(ord[i]+(" ")+antall[i]);
}
utfil.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
最佳答案
/The problem is located here somewhere:
Scanner keepTrack=infill.next();
while(keepTrack.next().Equals(null)){
fortelling=innfil.nextLine().toLowerCase().split(" ");
ord[0]=innfil.next().toLowerCase();
for(int i=0; i<fortelling.length; i++){
for(int j=0; j<5000; j++){
if(fortelling[i].equals(ord[j])){
antall[j]+=1;
System.out.print("heo");
}else{
ord[j]=fortelling[i];
antall[j]+=1;
antUnikeOrd+=1;
}
System.out.println(ord.length);
System.out.println(antUnikeOrd);
}
}
infill=infill.next();
keepTrack=infill;
}
innfil.close();
}
试试这个,我不确定它是否有效!
我认为问题在于您仅在一个元素上循环,而不是在所有元素上循环。
祝你好运!!!
关于java - 无限 while 循环以及读取文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19421729/