2012-06-18 4 views
0

파일을 읽고 해당 파일에 String이 몇 번 발생하는지 파악하려고합니다. 횟수에 따라 플레이어와 다른 대화를 표시합니다 (게임입니다). 여기에 내 코드Java - 파일을 읽고 int를 반환하는 동안 NullPointerException이 발생했습니다.

/** 
* Selects which dialogue to send depending on how many times the player has been jailed 
* @return The dialogue ID 
*/ 
public static int selectChat() { 
    System.err.println("Got to selectChar()"); 
    FileUtil.stringOccurrences(c.playerName, // NULLPOINTER HAPPENS HERE 
     "./data/restrictions/TimesJailed.txt"); 

    if (FileUtil.stringCount == 1) 
     return 495; 
    if (FileUtil.stringCount == 2) 
     return 496; 
    if (FileUtil.stringCount >= 3) { 
     return 497; 
    } 

    return 0; 
} 

이며, 다음이 실제 파일 읽기 방법 여기

public static int stringCount; 

/** 
* @param string 
* @param filePath 
* @return How many occurrences of the string there are in the file 
*/ 
public static int stringOccurrences(String string, String filePath) { 
    int count = 0; 

    try { 
     FileInputStream fstream = new FileInputStream(filePath); 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String strLine; 

     while ((strLine = br.readLine()) != null) { 
      if (strLine.contains(string)) 
       count++; 
     } 

     in.close(); 
    } 
    catch (Exception e) { // Catch exception if any 
     System.err.println("Error: " + e.getMessage()); 
    } 

    System.err.println(count); 
    stringCount = count; 
    return count; 
} 

Client c; 

public Jail(Client c) { 
    this.c = c; 
} 

누군가가 나에게 문제를 해결하는 데 도움 시겠어요 전 C와 함께 할 모든 것입니다 .

+0

것은 c.playerName가 null인지 여부를 알아 인쇄 해보십시오 (에서 System.out.println (c.playerName == NULL)) 바로 내가 그것을 알아 냈 FileUtil.stringOccurences (..) –

+0

을하기 전에,하지만 난 왜 내 자신의 질문에 대답 할만 큼 없기 때문에 당신을 보여줄 수 없습니다. 또는 7 시간 더 기다려야합니다 ... 도움을 주셔서 감사합니다! – Zomby

답변

0

cc.playerName은 null입니다.

이 null 인 경우에도 FileUtil에 따라 NullPointerException이 발생할 수 있습니다. 지금까지 내가 말할 수있는 같은 NPE 던질 수

0

귀하의 stringOccurrences 방법 - 그것은 try/catch 블록 밖에있는 역 참조하지 않습니다.

여기서 c에 값을 할당 하시겠습니까? null 인 경우 c.playerName을 읽으려는 시도는 NullPointerException입니다. 이러한 일이 발생했는지 확인하려면 코드를 다음으로 변경하십시오.

String myPlayerName = c.playerName; //now does NPE happen here ... 
FileUtil.stringOccurrences(myPlayerName, // or here? 
     "./data/restrictions/TimesJailed.txt"); 
+0

edited main post 내가 C로 무엇을하는지 보여주기 – Zomby

+0

String myPlayerName – Zomby

+0

에서 발생하므로'c'는'null'이어야합니다. 추가 정보가 있으면 감옥 (클라이언트 c)의 호출자가 'null'을 전달하고 있음을 의미합니다. –

0

아래와 같이 생성자를 작성하십시오.

Client c; 

    public Jail(Client c) { 
    if(c == null) { 
     c = new Client(); 
    } 
    } 
관련 문제