-1

我需要一些帮助来理解为什么我的代码不允许我输入一个文件名供它读取,然后它会处理它。我将粘贴下面的代码。我还想知道一件事:我需要代码来检查整个文本文件,检查一个数组是否已经在其中,然后将 +1 添加到我得到的计数器数组中。我无法测试它,所以我希望它有效!但是,如果有人可以快速浏览一下,看看他们的脸上是否有任何明显的错误,那就太棒了。:)

代码:

import java.util.*;
import java.io.*;

class Oblig3A{
    public static void main(String[]args){


//The problem is here somewhere I believe:

    OrdAnalyse oa = new OrdAnalyse();
    String filArgs=args[0];
    oa.analyseMetode(filArgs);
    }
}

class OrdAnalyse{
    void analyseMetode(String filArgs){

    //Begynner med aa opprette alle variabler som trengs, disse deklareres rett under. De ligger her oppe bare for at jeg skal ha oversikten over de.
    Scanner input, innfil;
    String[] ord, fortelling;
    int[] antall;
    int antUnikeOrd;
    PrintWriter utfil;

    //Variables..
    input=new Scanner(System.in);
    ord=new String[5000];
    antall=new int[5000];
    antUnikeOrd=0;

    try{
        innfil=new Scanner(filArgs);
        //Naa skal jeg dele opp prosessen litt for aa faa inn funksjonaliteten for aa for eksempel sette alle ord til lowercase.

        //Here it says that as long as the file is longer, it will continue the while-loop, and for every line it will set 
the words to all lowercase, split the line on blanks, and then fill it into an array called fortelling. 
It will then run two nested for-loops which will make it check the entire ord-array for matches for every word in the fortelling-array, 
and if it finds a match it will increase the count-array antall +1 in the index where the word is found.
 Does it not find anything, it will save the word to the (hopefully) last index in the array, increase that index in antall with 1, and then increase the uniquewordcounter (antUnikeOrd) with 1.
 I hope this part will work out, but I must first be able to get the file...


        while(innfil.hasNext()){
        fortelling=innfil.nextLine().toLowerCase().split(" ");
            for(int i=0; i<fortelling.length; i++){
              for(int j=0; j<5000; j++){
                if(fortelling[i]==ord[j]){
                   antall[j]+=1;
                }else if(!fortelling[i].contains(ord[j])){
                   ord[j]=fortelling[i];
                   antall[j]+=1;
                   antUnikeOrd+=1;
               }
               System.out.print(fortelling[i]);
               System.out.print(fortelling.length);
               }  
           }
           }
       }catch(Exception e){
           e.printStackTrace();
       }
     }
   }

似乎完全无法打开文件......而且我不知道为什么。这最终会将所有信息写入它创建的另一个文件,但我还没有写这部分。

4

1 回答 1

1

3个问题

  • File在构造函数中使用参数,Scanner以便您不使用String

    innfil = new Scanner(new File(filArgs));

  • 用于.equals比较String内容。==运算符用于Object引用。

    if (fortelling[i].equals(ord[j])) {

  • 最后这个声明

    } else if (!fortelling[i].contains(ord[j])) {

将抛出一个数组,NPE因为ord在检查之前从未填充过数组。我建议使用 aMap<String, Integer>而不是数组来存储单词的出现。

于 2013-10-16T23:03:37.557 回答