Arrays.sort() NullPointerException problem

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 334 Views - Last Post: 04 December 2011 - 08:45 PM Rate Topic: -----

#1 gawdlyz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 27-October 11

Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 06:26 PM

here is my code. i am having trouble with the Sort button. it is supposed to sort the large jtextarea on the right.
line 161 is my problem. its probably very obvious, but i am extremely tired right now (less than 4 hours of rest in the last 38 hours..).

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;          
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
import java.util.Arrays;
public class DL06GrocList
{
  public static void main(String[] args) throws IOException
  {
    Toolkit   toolKitVar        = Toolkit.getDefaultToolkit();
    Dimension windowDimVar      = toolKitVar.getScreenSize();
    DL06GrocListClass myWindow = new DL06GrocListClass();
    mywindow.setSize(500,300);
    mywindow.setLocation(windowDimVar.width/2-250,windowDimVar.height/2-150);
    mywindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mywindow.setVisible(true);
  }
}//end driver class

//==============================================================================
class DL06GrocListClass extends JFrame
{
  JTextArea grocListTa;                                                 //fields
  JButton   itemBtnList[];//array of 8 item buttons
  JButton   sortBtn;
  JButton   writeBtn;
  JButton   clearBtn;
  
  
  
  //----------------------------------------------------------------------------
  public DL06GrocListClass()	throws IOException                      //constructor
  {
    super("Grocery List - ");
    setLayout(new BorderLayout(0,0)); //0,0 gaps

    setUpNorth();
    setUpWest();     //method calls
    setUpCenter();
    setUpSouth();

    ItemBtnHandler itemBtnHdlr = new ItemBtnHandler();
    for(int i=0;i<8;i++)                             //add 8 item buttons
      itemBtnList[i].addActionListener(itemBtnHdlr); //to one handler

    SortHandler  sortHdlr   = new SortHandler();
    sortBtn.addActionListener(sortHdlr);
    
    WriteHandler writeHdlr  = new WriteHandler();
    writeBtn.addActionListener(writeHdlr);
    
    ClearHandler clearHdlr  = new ClearHandler();
    clearBtn.addActionListener(clearHdlr);
    //code must be added for other handlers

  }//end constructor
  //----------------------------------------------------------------------------
  private void setUpNorth()                                             //method
  {
    JLabel dateLabel;
    String date = P06StaticDateUtility.getAlphaDate();
    dateLabel   = new JLabel(date);
    dateLabel.setHorizontalAlignment(JLabel.CENTER);
    add(dateLabel,BorderLayout.NORTH);
  }
  //----------------------------------------------------------------------------
  private void setUpWest()                                              //method
  {
    FileReader      diskIn;
    BufferedReader  fileIn;
    String          rec;
    int             i = 0;

    itemBtnList       = new JButton[8];   //array of JButton
    JPanel westPanel  = new JPanel();
    westPanel.setLayout(new GridLayout(8,1));

    try
      {
        diskIn  =  new FileReader("basicItems.txt"); //8 items for buttons
        fileIn  =  new BufferedReader(diskIn);
        while(i<8)               //button list hard coded for 8 items only
          {
            rec            = fileIn.readLine(); //read items for buttons
            itemBtnList[i] = new JButton(rec);  //create new button
            westPanel.add(itemBtnList[i]);      //add to container
            i++;
          }
      }
    catch(IOException e)
      {
        JOptionPane.showMessageDialog(null,"Unable to open input file");
        System.exit(1);  //shut down, application not usable
      }

    add(westPanel,BorderLayout.WEST);
  }
  //----------------------------------------------------------------------------
  private void setUpCenter()                                            //method
  {
    grocListTa           = new JTextArea  ();  //the big area for the list
    JScrollPane  scrollp = new JScrollPane(grocListTa);
    add(scrollp,BorderLayout.CENTER);
  }
  //----------------------------------------------------------------------------
  private void setUpSouth()                                             //method
  {
    sortBtn             = new JButton("Sort");
    writeBtn            = new JButton("Write");
    clearBtn            = new JButton("Clear List");
    JPanel buttonPanel  = new JPanel();
    buttonPanel.setLayout(new GridLayout(1,3));
    buttonPanel.add(sortBtn);
    buttonPanel.add(writeBtn);
    buttonPanel.add(clearBtn);
    add(buttonPanel,BorderLayout.SOUTH);
  }

  //=================== event handlers - inner classes =========================
  private class ItemBtnHandler implements ActionListener          //item buttons
  {
    public void actionPerformed(ActionEvent e)
    {
	    String txtStr;
    	String btnTxt;

    	txtStr   = grocListTa.getText();       //get current list
    	btnTxt   = e.getActionCommand();    //get text from button

    	if(txtStr.length()==0)
    	  txtStr   = btnTxt;                //start list
    	else
    	  txtStr   = txtStr + "\n" + btnTxt; //replace list

    	grocListTa.setText(txtStr);
        
    }
  }//end item button inner class
  //----------------------------------------------------------------------------
  private class SortHandler    implements ActionListener                  //sort
  {
    public void actionPerformed(ActionEvent e)
    {
	    //jtextarea to string
		String textstr = grocListTa.getText();
		
		//string to array
		StringTokenizer stok	= new StringTokenizer(textstr);
		String[] temparray 		= new String [stok.countTokens()];
		
		int x=0;
		
		while(stok.hasMoreTokens()) 
		{
		     temparray[x] = stok.nextToken();
		     
		    
		    //sort array
		    Arrays.sort(temparray);
		    //array to jtextarea
		    StringBuffer sortedlist = new StringBuffer();
		    if (temparray.length > 0) 
		    {
		        sortedlist.append(temparray[0]);
		        for (int c=1; c<temparray.length; c++) 
		        {
		            sortedlist.append(temparray[c]);
		        }
		    }
		    
		grocListTa.setText(sortedlist.toString());
		x++;
		}
        //add code
    }
  }//end sort inner class
  //----------------------------------------------------------------------------
  private class WriteHandler   implements ActionListener                 //write
  {
    public void actionPerformed(ActionEvent e)
    {
	    FileWriter     fw;
		BufferedWriter bw;
		String         svar;
		
		try
		  {
		    fw   = new FileWriter("DL-groc-list.txt");
		    bw   = new BufferedWriter(fw);
		    svar = grocListTa.getText();
		    bw.write(svar);
		    bw.close();
		    JOptionPane.showMessageDialog(null,"Write successful:\n\n" + svar);
		  }
		catch(IOException x)
		  {
		    JOptionPane.showMessageDialog(null,"Output file error has occurred");
		  }
        
    }
  }//end write inner class
  //----------------------------------------------------------------------------
  private class ClearHandler   implements ActionListener                 //clear
  {
    public void actionPerformed(ActionEvent e)
    {
	    grocListTa.setText("");
        //add code
    }
  }//end clear inner class
  //----------------------------------------------------------------------------

}//end outter class (frame)




here is the output..

---------- Capture Output ----------
> "C:\Program Files (x86)\Java\jdk1.6.0_23\bin\java.exe" DL06GrocList
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at java.lang.String.compareTo(String.java:1167)
	at java.lang.String.compareTo(String.java:92)
	at java.util.Arrays.mergeSort(Arrays.java:1144)
	at java.util.Arrays.sort(Arrays.java:1079)
	at DL06GrocListClass$SortHandler.actionPerformed(DL06GrocList.java:161)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
	at java.awt.Component.processMouseEvent(Component.java:6267)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
	at java.awt.Component.processEvent(Component.java:6032)
	at java.awt.Container.processEvent(Container.java:2041)
	at java.awt.Component.dispatchEventImpl(Component.java:4630)
	at java.awt.Container.dispatchEventImpl(Container.java:2099)
	at java.awt.Component.dispatchEvent(Component.java:4460)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
	at java.awt.Container.dispatchEventImpl(Container.java:2085)
	at java.awt.window.dispatchEventImpl(window.java:2478)
	at java.awt.Component.dispatchEvent(Component.java:4460)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
> Terminated with exit code 0.


thanks for your time and help

Is This A Good Question/Topic? 0
  • +

Replies To: Arrays.sort() NullPointerException problem

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 9044
  • View blog
  • Posts: 33,555
  • Joined: 27-December 08

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 06:32 PM

Your problem is that you are sorting the array each time in the loop. Since the StringTokenizer class is legacy code anyways, just use the String split() method and sort the returned array.
String[] tokens = someString.split(" ");
Arrays.sort(tokens);


Was This Post Helpful? 0
  • +
  • -

#3 gawdlyz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 27-October 11

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 06:43 PM

how do i implement this solution? im still new to this damn swing gui. i recognize the issue now, although i cannot see where i should put the .split line. arrays.sort(tokens) goes before the while loop, correct?

my objective is to sort the jtextarea on the right, then display it in the same jtextarea.
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 9044
  • View blog
  • Posts: 33,555
  • Joined: 27-December 08

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 06:50 PM

It has nothing to do with Swing. Rather than creating a StringTokenizer and looping through to assign each token to an array element, simply use the String split() method to cut out the extra array, the loop, and the StringTokenizer. My sample above is all you need in the ActionListener to accomplish that task.
Was This Post Helpful? 1
  • +
  • -

#5 gawdlyz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 27-October 11

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 06:57 PM

im also trying to display it back in the text area.
right now with this code it just displays the first button that is clicked, and does not display the rest of the tokens[]


 private class SortHandler    implements ActionListener                  //sort
  {
    public void actionPerformed(ActionEvent e)
    {
	    //jtextarea to string
		String textstr = grocListTa.getText();
		
		String[] tokens = textstr.split("\n");
		Arrays.sort(tokens);
		
		int x=0;
		
		for(x=0; x<tokens.length; x++)
		{
			int i = 0;
		    grocListTa.setText(tokens[i]);
		    i++;
	    }
    }
  }

Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 9044
  • View blog
  • Posts: 33,555
  • Joined: 27-December 08

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 06:59 PM

The JTextArea has an append() method you can use. You can also manually build the String yourself, then setText() on the JTextArea after the loop.
Was This Post Helpful? 0
  • +
  • -

#7 gawdlyz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 27-October 11

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 07:11 PM

 private class SortHandler    implements ActionListener                  //sort
  {
    public void actionPerformed(ActionEvent e)
    {
	    String build = "";
	    //jtextarea to string
		String textstr = grocListTa.getText();
		
		String[] tokens = textstr.split("\n");
		Arrays.sort(tokens);
		
		int x=0;
		
		for(x=0; x<tokens.length; x++)
		{
			int i = 0;
		    build = tokens[i] + "\n";
		    i++;
	    }
	    grocListTa.setText(build);
    }
  }


returns:

"bread" after clicking the "bread" "milk" and "eggs" buttons in any order. so now this is just a problem of finding why it is not filling the tokens[] array past the first element.
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8032
  • View blog
  • Posts: 31,202
  • Joined: 06-March 08

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 07:18 PM


for(x=0; x<tokens.length; x++)
       {
           int i = 0;
           grocListTa.setText(tokens[i]);
           i++;   // kind of useless to set i++ here


at the next ireation you will do

int i = 0;
Was This Post Helpful? 0
  • +
  • -

#9 gawdlyz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 27-October 11

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 07:56 PM

ireation? is that a typo? im getting a little more frustrated by the minute. why is it useless to set i++ inside the loop?

i should have put the int i=0 outside the loop yes i see now. still having the same issue only it's not returning alphabetically. just returns the first button clicked now.
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8032
  • View blog
  • Posts: 31,202
  • Joined: 06-March 08

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 07:59 PM

Let see what happens with is code
for(x=0; x<tokens.length; x++)
       {
           int i = 0;

           grocListTa.setText(tokens[i]);
           i++; 
}



int x = 0;
loop:
if x == tokens.length goto done
int i = 0; // setting (or resseting :) i to 0
grocListTa.setText(tokens[i]); so setText(tokens[0])
i = i + 1; // so i == 1
x = x + 1;
goto loop
done:

so you will always setText(tokens[0]) as you reset i to 0 in the loop
Was This Post Helpful? 1
  • +
  • -

#11 gawdlyz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 27-October 11

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 08:14 PM

i moved it, still having the same issue. i believe it is because tokens[] is not being loaded past tokens[0]. it could also be that i am using the delimiter \n in my string.split() call.
Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8032
  • View blog
  • Posts: 31,202
  • Joined: 06-March 08

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 08:20 PM

View Postgawdlyz, on 04 December 2011 - 11:14 PM, said:

i moved it, still having the same issue. i believe it is because tokens[] is not being loaded past tokens[0]. it could also be that i am using the delimiter \n in my string.split() call.

?????

as long you use tokens.length you won't get out of bound
Not sure what you try to do by may be
for(x=0; x<tokens.length; x++)
{
           grocListTa.setText(tokens[x] + "\n");
}


will do the trick

This post has been edited by pbl: 04 December 2011 - 08:21 PM

Was This Post Helpful? 0
  • +
  • -

#13 gawdlyz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 27-October 11

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 08:27 PM

objective:
click buttons and display the button text in jtextarea - done
sort jtextarea then display in jtextarea a-z - incomplete
write - complete
clear - complete

all i am trying to do is get it to display the damn jtextarea just like this when all the buttons are clicked: (with extra spaces or blank lines removed)

bread
cereal
chicken
coke
eggs
hamburger
laundry soap
milk

as of right now it just displays the word whose first letter is closest to "z" aka milk
Was This Post Helpful? 0
  • +
  • -

#14 gawdlyz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 27-October 11

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 08:33 PM

your solution does not work
Was This Post Helpful? 0
  • +
  • -

#15 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8032
  • View blog
  • Posts: 31,202
  • Joined: 06-March 08

Re: Arrays.sort() NullPointerException problem

Posted 04 December 2011 - 08:37 PM

it wasn't a solution... I was jus tring to understand what you tried to do
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2