Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 16 of 16

Thread: Problem with NullPointerException?

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Problem with NullPointerException?

    Ok, so I'm working with returning an array in my program, StudentGrades

    In this block, once my button construct is hit... it creates the array

    if(e.getActionCommand().equals("Construct"))
    			{
    				sg =  new StudentGrades(students);
    				scores = new int[students];				
     
    				JOptionPane.showMessageDialog(null,"Created");
    			}

    In the next block, once Action Button 1 is pressed, it should return a copy of the array

    if(e.getActionCommand().equals("Action 1"))
    			{
    				scores = sg.getTestGrades();
     
    				for(int i = 0; i < scores.length; i++)
    				{
    					area[0].setVisible(true);
    					area[0].append(scores[i]+ " ");
    				}
    			}


    Here's the getTestGrades method
    public int[] getTestGrades()
    	{
    		int[] testGrades = new int[studentGrades.length];
    		int value = 0;
    		for(int i = 0; i < studentGrades.length; i++)
    		{
    			testGrades[i]= studentGrades[i];
     
    		}
    		return testGrades;
     
    	}

    And here's the error that comes up

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at StudentGUI.actionPerformed(StudentGUI.java:89)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.jav a:6267)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3267)
    at java.awt.Component.processEvent(Component.java:603 2)
    at java.awt.Container.processEvent(Container.java:204 1)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4630)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2099)
    at java.awt.Component.dispatchEvent(Component.java:44 60)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4577)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2478 )
    at java.awt.Component.dispatchEvent(Component.java:44 60)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 599)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problem with NullPointerException?

    Maybe you never initialized the array.

    Or the button.

    It could be because scores is defined inside an if statement and may not have a scope beyond that if statement so it could be there but be null.

  3. #3
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problem with NullPointerException?

    if(e.getActionCommand().equals("Action 1"))
    {
    scores = sg.getTestGrades();

    for(int i = 0; i < scores.length; i++)
    {
    area[0].setVisible(true);
    area[0].append(scores[i]+ " ");
    }
    }

    hmmmm....did you mean area[i] instead of area[0]?

  4. #4
    Junior Member
    Join Date
    Oct 2010
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Problem with NullPointerException?

    No, I mean area[0]. I specifically have an array of 8 JTextAreas, used in a JLayeredPane.

    Here's the fields in StudentGUI
     private int[] scores;
    		private int[] sorted;
    		static JButton[] action;
    		static JTextArea[] area;

  5. #5
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problem with NullPointerException?

    You only need to tell it to set visible once. Sometimes I've done it more than once, by accident, or just to figure out why it wasn't showing up, but a for loop to keep telling it that seems kind of silly.

    A good idea would be to define area[], sq, and especially studentGrades.

    In fact, it appears that StudentGrades is a class.

    While you can make a class an array, I think that perhaps that you should probably change

    public int[] getTestGrades()
    	{
    		int[] testGrades = new int[studentGrades.length];
    		int value = 0;
    		for(int i = 0; i < studentGrades.length; i++)
    		{
    			testGrades[i]= studentGrades[i];
     
    		}
    		return testGrades;
     
    	}

    to

    public int[] getTestGrades()
    	{
    		int[] testGrades = new int[scores.length];
    		int value = 0;
    		for(int i = 0; i < scores.length; i++)
    		{
    			testGrades[i]= scores[i];
     
    		}
    		return testGrades;
     
    	}

    and try to get a method that returns the number of students, like

    Then define sq in your constructor.

    area may not have been defined, I don't have the whole code so I can't exactly say.

    I'm assuming area is a JTextArea array.

    It appears you only made it for element 0, so why do an array at all?

    Even if StudentGrades is an array, it's possible you never put anything in it.

  6. #6
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Lightbulb Re: Problem with NullPointerException?

    Was sq first defined in your actionPerformed(ActionEvent e) method, inside that if statement for the button "Construct"?

    sg = new StudentGrades(students);

    If so, then it won't know what sq is because it didn't go to the if statement it won't have been initialized, and it won't throw a compiler error because sq has been defined in your constructor probably, but it didn't have it initialized due to scope, and so you called a method with an uninitialized variable, which throws a Null Pointer Exception.

    Define sq before the if statements if you can. That way it'll be accessible in all the if statements.

  7. #7
    Junior Member
    Join Date
    Oct 2010
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Problem with NullPointerException?

    Well, I do have it defined.

    Here's the full code
    [highlight = Java] import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
     
    public class StudentGUI extends JFrame
    	implements ActionListener
    	{
    		private int[] scores;
    		private int[] sorted;
    		static JButton[] action;
    		static JTextArea[] area;
    		static JFrame frame;
     
    		public StudentGUI()
    		{
    			super("StudentGrades.java");
    			action = new JButton[9];
    			action[0] = new JButton("Construct");
    			action[0].addActionListener(this);
    			action[0].setMnemonic(KeyEvent.VK_C);
     
    			for(int i = 1; i < action.length; i++)
    			{
    				action[i] = new JButton("Action " + i);
    				action[i].addActionListener(this);
    				action[i].setVisible(true);
    			}
    			frame = new JFrame("Action Window");
    			frame.getLayeredPane();
    			frame.setBounds(200,200,140,140);
    			frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    			frame.setVisible(true);
     
    			area = new JTextArea[8];
    			for(int i = 0; i < area.length; i++)
    			{
    				area[i] = new JTextArea();
    				area[i].setLineWrap(true);
    				area[i].setEditable(false);
    				area[i].setVisible(false);
    				frame.add(area[i]);
    			}
     
    			Container c = getContentPane();
    			JPanel buttonPanel = new JPanel(new GridLayout(1,9));
    			for(int i = 0; i < action.length; i++)
    			{
    				buttonPanel.add(action[i]);
    			}
    			c.setBackground(Color.white);
    			c.add(buttonPanel, BorderLayout.CENTER);
     
     
     
    		}
    		public void actionPerformed(ActionEvent e)
    		{
     
     
    			Random r = new Random();
     
    			StudentGrades sg = null;
    			int students = r.nextInt(21)+1;
     
     
     
    			if(e.getActionCommand().equals("Construct"))
    			{
    				sg =  new StudentGrades(students);
    				scores = new int[students];				
     
    				JOptionPane.showMessageDialog(null,"Created");
    			}
     
     
     
     
     
    			if(e.getActionCommand().equals("Action 1"))
    			{
    				scores = sg.getTestGrades();
     
    				for(int i = 0; i < scores.length; i++)
    				{
    					area[0].setVisible(true);
    					area[0].append(scores[i]+ " ");
    				}
    			}
    			if(e.getActionCommand().equals("Action 2"))
    			{
    				sorted = sg.selectionSortB(scores);
    				for(int i = 0; i < scores.length; i++)
    				{
    					area[1].setVisible(true);
    					area[1].append(sorted[i] + " ");
    				}
    			}
    			/*if(e.getActionCommand().equals(action[3].getText()))
    			{
    				area[2].setVisible(true);
    				if(sg.issEqual(scores)== true)
    					area[2].append("The Arrays are Equal");
    				else
    					area[2].append("The Arrays are not Equal");
    			}*/
    			if(e.getActionCommand().equals(action[4].getText()))
    			{
    				int highest = sg.highestGrade(sorted);
    				area[3].setVisible(true);
    				area[3].append("The Highest Value is " + highest);
    			}
    			if(e.getActionCommand().equals(action[5].getText()))
    			{
    				int lowest = sg.lowestGrade(sorted);
    				area[4].setVisible(true);
    				area[4].append("The lowest Value is " + lowest);
    			}
    			if(e.getActionCommand().equals(action[6].getText()))
    			{
    				int median = sg.medianGrade(sorted);
    				area[5].setVisible(true);
    				area[5].append("The median Value is " + median);
    			}
    			if(e.getActionCommand().equals(action[7].getText()))
    			{
    				double average = sg.averageGrade(sorted);
    				area[6].setVisible(true);
    				area[6].append("The Average Value is " + average);
    			}
    			if(e.getActionCommand().equals(action[8].getText()))
    			{
    				int mode = sg.modeGrade(sorted);
    				area[7].setVisible(true);
    				area[7].append("The Mode is " + mode);
    			}
     
     
    		}
    	}[/highlight]

    and StudentGrades

    import java.util.Random;
    public class StudentGrades
    {
    	private int[] studentGrades;
    	public StudentGrades(int students)
    	{
    		Random r = new Random();
    		studentGrades = new int[students];
    		for(int i = 0; i < studentGrades.length; i++)
    		{
    			studentGrades[i] = r.nextInt(101);
    		}
     
    	}
    	public int[] getTestGrades()
    	{
    		int[] testGrades = new int[studentGrades.length];
    		int value = 0;
    		for(int i = 0; i < studentGrades.length; i++)
    		{
    			testGrades[i]= studentGrades[i];
     
    		}
    		return testGrades;
     
    	}
    	public int[] selectionSortB(int[] nums)
       {
       		int size = nums.length;
          //  Same as version A, but sorts in ascending order
     
          int first, current, least, temp;
     
          for(first = 0; first < size; first = first + 1)
          {
             least = first;
             for(current = first+1; current < size; current = current + 1)
             {  if (nums[current] < nums[least])
                {  least = current; }
             }
             temp = nums[least];
             nums[least] = nums[first];
             nums[first] = temp;
          }
          return nums;
       }
       /*public boolean isEqual(int[] arr)
       {
       }*/
       public int highestGrade(int[] arr)
       {
       		int max = 0;
       		for(int i = 0; i < arr.length; i++)
       		{
       			if(arr[i] > max)
       			{
       				max = arr[i];
       			}
     
       		}
       		return max;
       }
       public int lowestGrade(int[] arr)
       {
       		int min = arr[0];
       		for(int i = 1; i < arr.length; i++)
       		{
       			if(arr[i] < min)
       				min = arr[i];
     
       		}
       		return min;
       }
       public double averageGrade(int[] arr)
       {
       		double total = 0.0;
       		for(int i = 0; i < arr.length; i++)
       		{
       			total += (double)arr[i];
       		}
       		double avg = total / arr.length;
       		return avg;
       }
       public int medianGrade(int[] arr)
       {
       		int median = (arr[0] + arr[arr.length - 1]) / 2 ;
       		return median;
       }
       public int modeGrade(int[] arr)
       {
       		int[] count = new int[arr.length];
       		for(int i = 0; i < arr.length; i++)
       		{
       			count[i]++;
       		}
       		int max = 0;
       		for(int i = 0; i < count.length; i++)
       		{
       			if(count[i] > max)
       			{
       				max  = count[i];
       			}
       		}
       		return count[max];
     
       }
     
    }
    Last edited by scooty199; November 6th, 2010 at 04:32 PM.

  8. #8
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problem with NullPointerException?

    Did you ever set action[0] to visible?

  9. #9
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problem with NullPointerException?

    StudentGrades sg = null;

    Why null?

  10. #10
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problem with NullPointerException?

    StudentGrades sq = null;
    scores = sg.getTestGrades();

    yeah, your first if statement may define sq, but if the if condition is false, it won't go there. So it'll still be null.

  11. #11
    Junior Member
    Join Date
    Oct 2010
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Problem with NullPointerException?

    Because it order for my program requirements to be met, it had to be instantiated at some point, but the program requirements wouldn't have been met if I just had it set as

    StudentGrades sg = null;

  12. #12
    Junior Member
    Join Date
    Oct 2010
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Problem with NullPointerException?

    I've also tested the first if statement, if it's true it'll come up with a box saying created. So it does create it.

  13. #13
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problem with NullPointerException?

    Well, you didn't define it before

    scores = sg.getTestGrades();

    so it's still null.

    That's why I was asking why it is null there.

    You could always have the method click the construct button if it is null.

    if (sq == null)
    {
    action[0].doClick();
    }

    scores = sg.getTestGrades();

    In short, you never assign sq a value, in that if (e.getActionCommand().equals("Action 1"))

    so it's still null.

  14. The Following User Says Thank You to javapenguin For This Useful Post:

    scooty199 (November 6th, 2010)

  15. #14
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,237
    Thanks
    176
    Thanked 817 Times in 760 Posts
    Blog Entries
    5

    Default Re: Problem with NullPointerException?

    This is a scope problem. The code may create an instance of StudentGrades, but when the actionPerformed method exits it ends the variable scope - eg no more StudentGrades instance. Move it to be an instance variable of the class (eg outside the method) so once it is created there still is a reference to the object.

  16. The Following 2 Users Say Thank You to copeg For This Useful Post:

    javapenguin (November 6th, 2010), scooty199 (November 6th, 2010)

  17. #15
    Junior Member
    Join Date
    Oct 2010
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Problem with NullPointerException?

    Ah, I wasn't thinking that. I'll try that. Thanks.

    And thank you javapenguin.

  18. #16
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Problem with NullPointerException?

    Quote Originally Posted by copeg View Post
    This is a scope problem. The code may create an instance of StudentGrades, but when the actionPerformed method exits it ends the variable scope - eg no more StudentGrades instance. Move it to be an instance variable of the class (eg outside the method) so once it is created there still is a reference to the object.
    I thought that might be the case.

Similar Threads

  1. [SOLVED] Nullpointerexception
    By kbwalker87 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: October 14th, 2010, 10:33 PM
  2. [SOLVED] NullPointerException
    By javapenguin in forum What's Wrong With My Code?
    Replies: 13
    Last Post: October 1st, 2010, 12:10 AM
  3. NullPointerException
    By bbr201 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 29th, 2010, 07:06 PM
  4. problem in java.lang.NullPointerException
    By jianghuzai in forum What's Wrong With My Code?
    Replies: 6
    Last Post: July 28th, 2010, 10:24 AM
  5. NullPointerException:null problem
    By derky in forum Exceptions
    Replies: 8
    Last Post: September 18th, 2009, 03:06 PM