2013-10-16 17 views
-1

我需要一些幫助,理解爲什麼我的代碼不會讓我放入一個文件名以供它讀取,然後處理。我將粘貼下面的代碼。我還想知道一件事情:我需要代碼來檢查整個文本文件,檢查數組是否已經存在,然後將+1添加到我獲得的計數器數組中。我一直無法測試它,所以我希望它能起作用!但如果有人能夠快速瀏覽一下,看看他們臉上是否有尖叫的錯誤,那將是非常棒的。 :)Java無法讓我自己從終端args獲取文件名[0]

代碼:

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(); 
     } 
    } 
    } 

這似乎完全無法打開文件...我不知道爲什麼。這將最終寫出所有信息到它創建的另一個文件,但我還沒有寫這個部分。

+0

似乎這是一個糟糕的問題,因爲它被downvoted? – Makri

回答

1

3個問題

  • Scanner構造使用File說法,這樣你不使用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陣列被檢查之前是從來沒有填充。我建議使用Map<String, Integer>而不是數組來存儲單詞的出現次數。

+0

嗯... NullPointerException在第9行,這意味着oa.analyseMode(filArgs) - 行O.o – Makri

+0

是的,不是唯一的問題 – Reimeus

+0

好吧,非常感謝。這很清楚爲什麼我現在將NPE列入你所描述的範圍。我會嘗試找到一種方法來解決它:) – Makri