无明显原因的空指针异常

时间:2013-03-21 16:58:26

标签: java

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

}

2 个答案:

答案 0 :(得分: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];

正如评论部分中 Luiggi Mendoza 所述,words方法中定义的局部变量makeArrayshadowing实例变量wordsHUTPanel类中定义。

作为旁注 我想指出每次在{{1}中调用时,方法BufferedReader中不必要地创建新的grabText()个对象}}。如果您在类中使用getTheText()个实例变量,并使用inputReaderconstructor内实例化一次,那么效率会非常高。这样,您的inputReader = new BufferedReader(new InputStreamReader(System.in));方法就像这样:

grabText

答案 1 :(得分:0)

确保始终始终使用选项7,以便初始化words数组。事实上,这不是用户应该做的事情。应用程序应该处理它,以便用户不能选择其他选项,或自动执行。

更新 Vishal K 是正确的,但这仍然是您应用中的弱点。