0

堆栈溢出。我正在尝试制作一个程序,该程序使用文本菜单来处理大量事物来操作单个字符串。其中一种方法将字符串转换为字符串数组。这工作正常。但是,所有将其作为数组操作的方法(一个将其打印出来,一个反转字序,一个使用交换排序方法对其进行排序)在调用时返回 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]);
    }
}

}
4

2 回答 2

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定义的局部变量是在类中定义的实例变量的影子。作为旁注,我想指出每次调用方法时在方法中不必要地创建新对象。如果你在你的类中创建一个实例变量,并在using 中实例化一次它会非常有效。这样你的方法就变成了这样:makeArraywordsHUTPanel

BufferedReadergrabText()getTheText()inputReaderconstructorinputReader = 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;

}
于 2013-03-21T17:02:38.233 回答
0

确保你总是从选项 7 开始,这样你的words数组就会被初始化。这实际上不是用户应该做的事情。应用程序应该处理它,这样用户要么不能选择其他选项,要么自动选择。

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

于 2013-03-21T17:03:40.550 回答