2013-03-21 4 views
0

StackOverflow. Я пытаюсь сделать программу, которая использует текстовое меню для множества вещей, чтобы манипулировать одной строкой. Один из методов превращает строку в массив строк. Это прекрасно работает. Тем не менее, все методы, которые манипулируют им как массив (один отпечатывает его, меняет порядок слов, а один сортирует их с помощью метода сортировки Exchange) возвращает при вызове исключение NullPointerException. Я просмотрел весь код и не вижу, откуда он. Вот файл .Java, содержащий весь код. Моя проблема происходит только тогда, когда я вызываю методы printArray(), reverse() и sort(), расположенные внизу. Любая помощь приветствуется. Извините за неаккуратный код, я еще не очистил его.Исключения Null Pointer без видимой причины

Код:

/* 
Computer Programming Lab 11 
Jim Kimble 
3 Mar 2013 

Work with strings and implementing a menu. 

Acknowledgements: 
Uses main structure of HUTPanel as designed at UMU, 2002-2012 
*/ 

import java.io.*; 
import java.awt.*; 
import javax.swing.*; 


public class HUTPanel extends JPanel 
{ 
/*************************************************** 
* Class-level data members should be declared here. 
***************************************************/ 
int numVowels; 
String[] words; 
String str; 
String vowels; 
String menuChoice; 
String oString = "A tong lime ago, a daggy shog bossed a cridge over a pillmond,\n" 
       +"When in the course of human events\n" 
       +"Mary had a little lamb.\n" 
       +"The girls' basketball team repeated as tournament champion this weekend."; 




public HUTPanel(JFrame frame) 
{ 

    // Set panel background color 
    setBackground(Color.WHITE); 
    setLayout(null); 
    setPreferredSize(new Dimension(810, 410)); 

    /*************************** 
    * Now add your code below: 
    ***************************/ 

    // Create a frame around this panel. 
    frame.setTitle("Computer Programming Lab/Program # 11"); 
    frame.getContentPane().add(this); 

    str = "A tong lime ago, a daggy shog bossed a cridge over a pillmond,\n" 
      +"When in the course of human events\n" 
      +"Mary had a little lamb.\n" 
      +"The girls' basketball team repeated as tournament champion this weekend."; 

    System.out.println("Lab 11: Text Manipulation"); 
    //getTheText(); 
    System.out.println("The string is: '"+str+"'."); 

    handleTheMenu(); 

} // end of constructor 

/************************* 
    * Add your methods here: 
    *************************/ 

// Get a text sequence from the keyboard and put it in str 
public void getTheText() 
{ 
    Boolean inputDone = false; 

    while (!inputDone) 
    { 
     System.out.print("Enter your text: "); 
     inputDone = grabText(); 
    } 

} 

private Boolean grabText() 
{ 

    try { 
      BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)); 
      menuChoice = inputReader.readLine(); 
      return true; 
    } 
    catch(IOException e) 
    { 
     System.out.println("Error reading input. Please try again."); 
    } 

    return false; 

} 

public void handleTheMenu() 
{ 
    int choice = -1; 
    Boolean OK; 

    while (choice != 0) 
    { 
     choice = -1; 

     System.out.println("Menu:"); 
     System.out.println(); 
     System.out.println(" 1. Count the vowels"); //"There are ... vowels in the text." 
     System.out.println(" 2. Remove all letter e's"); //then print it. 
     System.out.println(" 3. Replace all t's with '+'"); //then print it 
     System.out.println(" 4. Search for a requested word (will reset the string)"); //Does 'word' exist in the text? 
     System.out.println(" 5. Print the words on individual lines"); 
     System.out.println(" 6. Reset the string.");//Reset the string to the original 
     System.out.println(" 7. Put the words in an array"); //then print it 
     System.out.println(" 8. Reverse the text word order"); //then print it 
     System.out.println(" 9. Sort the words in an array"); //Once the words are put into an array 
     System.out.println(); 
     System.out.print(" 0 to quit --> "); 

     OK = grabText(); 

     if (OK) 
     { 
      try 
      { 
       choice = Integer.parseInt(menuChoice); 
      } 
      catch(NumberFormatException e) 
      { 
       System.out.println("Not a number; please try again."); 
       System.out.println(); 
      } 

      switch(choice) 
      { 
       case 0: System.out.println(); 
         System.out.println("Thank you."); 
         break; 
       case 1: countVowels(); 
         break; 
       case 2: removeAllEs();        
         break; 
       case 3: changeTToPlus(); 
         break; 
       case 4: find(); 
         break; 
       case 5: listWords(); 
         break; 
       case 6: reset(); 
         break; 
       case 7: makeArray(); 
         break; 
       case 8: reverse(); 
         break; 
       case 9: sort(); 
         break; 
       default: System.out.println("Not a valid choice; please try again.");  
      } 
     } 
    } 
} 

private void countVowels() { 
    //count the vowels in str 
    vowels = "aeiouAEIOU"; 
    numVowels = 0; 
    for(int i = 0; i < vowels.length(); i ++) { 
     for(int j = 0; j < str.length(); j++) { 
      if (str.charAt(j) == vowels.charAt(i)) { 
       numVowels += 1; 
      } 
     } 
    } 
    System.out.println("The string has " + numVowels + " vowels in it."); 
} 

private void removeAllEs() { 
    String str3 = str.replace('e', ' '); 
    System.out.print(str3); 
    str = str3; 
} 

private void changeTToPlus() { 
String str2 = str.replace('t', '+'); 
System.out.println(str2); 
str = str2; 
} 

private void find() { 
    str = oString; 
    getTheText(); 
    if(str.indexOf(menuChoice) != -1) 
    { 
     System.out.println("The word " +menuChoice+ " is at index " +str.indexOf(menuChoice)); 
    } 
    else 
    { 
     System.out.println("The word " +menuChoice+ " is not in the string."); 
    } 
} 

private void listWords() { 
    int pos = 0; 
    int i = 0; 
    while(i > -1) 
    { 
     i = str.indexOf(' ', pos); 
     if (i > -1) 
     { 
     System.out.println(str.substring(pos, i)); 
     pos = i + 1; 
     } 
    } 
} 


private void reset() { 
    str = oString; 
    System.out.println(); 
    System.out.println("String reset."); 
    System.out.println(); 
} 

private void makeArray() { 
    int n = 1; 
    String[] words = new String[n]; 
    int pos = 0; 
    int i = 0; 
    int j = 0; 
    while(j > -1) 
    { 
     for (i = 0; i < 1000; i++) 
     { 
      n += 1; 
      j = str.indexOf(' ', pos); 
      if (j > -1) 
      { 
       words[i] = str.substring(pos, j); 
       pos = j + 1; 
      } 
     } 
    } 
    //printArray(); 
} 
//***FIX*** 
private void printArray() { 
     for (int k = 0; k < words.length -1; k++){ 
      System.out.println(words[k]); 
     } 
    } 

//***FIX*** 
private void reverse() { 
    int i = 0; 
    int j = words.length - 1; 
    String temp; 
    while (i < j){ 
     temp = words[i]; 
     words[i] = words[j]; 
     words[j] = temp; 
     i++; 
     j--; 
    } 
} 

private void sort() { 
    String temp = ""; 
    for (int i = 1; i < words.length - 1; i++) { 
     for (int j = i + 1; j < words.length; j++) { 
      int x = words[i].compareTo(words[j]); 
      if (x > 0) { 
       temp = words[i]; 
       words[i] = words[j]; 
       words[j] = temp; 
      } 
     } 
    } 
    for (int p = 0; p < words.length -1; p++) { 
     System.out.println(words[p]); 
    } 
} 

} 
+6

Пожалуйста, покажите stacktrace – PSR

+0

Скорее всего, вы пытаетесь вызвать методы перед вызовом других методов, которые задают переменную 'words'. –

+0

Я новичок в этом. Как найти стек? Я использую NetBeans 7.2.1, если это имеет значение. – user1191339

ответ

3

Вы Ошибка здесь:

private void makeArray() { 
    int n = 1; 
    String[] words = new String[n];//At This line you are creating local array words.The instance variable words is still null. 
    int pos = 0; 
    int i = 0; 
    int j = 0; 
    while(j > -1) 
    { 
     for (i = 0; i < 1000; i++) 
     { 
      n += 1; 
      j = str.indexOf(' ', pos); 
      if (j > -1) 
      { 
       words[i] = str.substring(pos, j); 
       pos = j + 1; 
      } 
     } 
    } 

использование:

words = new String[n]; вместо String[] words = new String[n];

Как отметил Луиджи Мендоса в комментарий s ection, локальная переменная words, определенная в методе makeArray, равна shadowing переменная экземпляра words, определенная в пределах HUTPanel класс.

Как примечание стороны Я хочу отметить ненужное создание новых BufferedReader объектов в методе grabText() каждый раз, когда вы вызываете его в getTheText(). Было бы очень эффективно, если бы ваша переменная экземпляра создавала переменную экземпляра в вашем классе и создавала ее один раз в пределах constructor, используя inputReader = new BufferedReader(new InputStreamReader(System.in));. Таким образом, ваш метод grabText становится так:

private Boolean grabText() 
{ 

    try { 
      //No more new object creation for BufferedReader for each call of this method. 
      menuChoice = inputReader.readLine(); 
      return true; 
    } 
    catch(IOException e) 
    { 
     System.out.println("Error reading input. Please try again."); 
    } 

    return false; 

} 
+1

Ошибка связана с [затенением] (http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15). Похоже, это то, что ты имеешь в виду. –

+0

@LuiggiMendoza: Да Точно .... –

+0

@ user1191339: вы все еще получаете исключения? –

0

Убедитесь, что вы всегда всегда начинаются с опцией 7, так что ваш words массив инициализируется. На самом деле это не то, что пользователь должен делать. Приложение должно обрабатывать его так, чтобы пользователь либо не мог выбирать другие параметры, либо автоматически.

Update: Вишал K правильно, но это по-прежнему слабым местом в вашем приложении.