2013-03-21 91 views
0

StackOverflow。我試圖製作一個程序,它使用文本菜單來處理大量的操作單個字符串。其中一種方法將字符串轉換爲字符串數組。這工作正常。但是,所有將其作爲數組操作的方法(一個打印出來,一個反轉詞序,一個使用交換排序方法對它們進行排序)在調用時會返回NullPointerException。我查看了所有的代碼,並沒有看到它來自哪裏。這裏是包含所有代碼的.Java文件。我的問題只發生在底部附近的printArray(),reverse()和sort()方法時。任何和所有的幫助表示讚賞。對不起草的代碼,我還沒有清理它。沒有明顯原因的空指針異常

代碼:

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

請顯示堆棧跟蹤 – PSR 2013-03-21 16:59:43

+0

您很可能在調用其他設置'words'變量的方法之前嘗試調用方法.. – 2013-03-21 17:01:03

+0

我對此很陌生。我如何找到堆棧跟蹤?如果它有所作爲,我正在使用NetBeans 7.2.1。 – user1191339 2013-03-21 17:04:50

回答

3

你的錯誤是在這裏:的

words = new String[n];代替String[] words = new String[n];

正如評論小號提及Luiggi門多薩

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

使用方法makeArray中定義的局部變量words方法是shadowing實例變量words定義在HUTPanel類中。

作爲旁註我想指出,新BufferedReader對象的不必要的創作每次都稱其爲getTheText()時間的方法grabText()。如果您的類中使用inputReader實例變量,並使用inputReader = new BufferedReader(new InputStreamReader(System.in));constructor內實例化一次,將會非常有效。這樣,你的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)。看起來這就是你的意思。 – 2013-03-21 17:04:56

+0

@LuiggiMendoza:是的...... – 2013-03-21 17:06:20

+0

@ user1191339:你還在收到異常嗎? – 2013-03-21 17:30:23

0

確保你總是你總是選擇7開始,所以你words數組被初始化。這實際上不是用戶應該做的事情。應用程序應該處理它,以便用戶不能選擇其他選項,或者自動執行。

更新維沙爾ķ是正確的,但是這仍然是在你的應用程序中的薄弱點。