2013-03-21 48 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数组被初始化。这实际上不是用户应该做的事情。应用程序应该处理它,以便用户不能选择其他选项,或者自动执行。

更新维沙尔ķ是正确的,但是这仍然是在你的应用程序中的薄弱点。