2012-06-18 4 views
0

Я пытаюсь прочитать файл и выяснить, сколько раз в этом файле происходит String. В зависимости от того, сколько раз он будет отображать другой диалог с игроком (это игра). Вот мой кодJava - NullPointerException при простом чтении файла и возврате int

/** 
* 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; 
} 

Может кто-то пожалуйста, помогите мне разработать проблему ,

+0

Попытайтесь напечатать или нет c.playerName является недействительным (System.out.println (c.playerName == NULL)) перед делать FileUtil.stringOccurences (..) –

+0

я понял это, но я не может показать вам, почему, потому что мне не хватает, чтобы ответить на мой собственный вопрос. Или я должен ждать еще 7 часов ... Спасибо за помощь! – Zomby

ответ

0

Мне кажется, что c в c.playerName - null.

Также в зависимости от того, что вы используете, NullPointerException также, если playerName - null.

0

Ваш метод stringOccurrences не может выбросить NPE, насколько я могу судить - он не делает различий вне блока try/catch.

Где вы назначаете значение c? Если он равен нулю, то ваша попытка прочитать c.playerName приведет к созданию NullPointerException. Чтобы убедиться, что это произошло, измените свой код на:

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

Редактированное главное сообщение, что я делаю с помощью c – Zomby

+0

Это происходит при String myPlayerName – Zomby

+0

Итак, 'c' должен быть' null'. С вашей добавленной информацией это означает, что вызывающий элемент 'Jail (Client c)' передается в 'null'. –

0

Пожалуйста, напишите ваш конструктор, как указано ниже;

Client c; 

    public Jail(Client c) { 
    if(c == null) { 
     c = new Client(); 
    } 
    } 
Смежные вопросы