The Artima Developer Community
Sponsored Link

Java Answers Forum
Please assist with NullPointer error....

7 replies on 1 page. Most recent reply: Jul 23, 2002 1:48 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 7 replies on 1 page
Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

Please assist with NullPointer error.... Posted: Jul 23, 2002 6:10 AM
Reply to this message Reply
Advertisement
most of the graphic components are commented out, I was just trying to implement an interface using gridBagLayout. Can someone tell me why the following code compiles good but returns a nullPointer exception when I run it. I sure would appreciate it, anything that can be added is ALWAYS appreciated. thankyou in advance!

// Fig. 10.21: DeckOfCards.java
// Card shuffling and dealing program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class DeckOfCards extends JFrame {
   private Card deck[];
   private Card myHand[];
   private Card hisHand[];
   private int currentCard;
   private JButton dealButton, shuffleButton, discardButton;
   private JTextField mDisplayCard1,mDisplayCard2,mDisplayCard3,mDisplayCard4,mDisplayCard5;
   private JTextField hDisplayCard1,hDisplayCard2,hDisplayCard3,hDisplayCard4,hDisplayCard5;
   private JLabel status, dealerTag, playerTag;
   // put private .gif actualCards[]; here 
   private int mCountFaces[];
   private int mCountSuits[];
   private int hCountFaces[];
   private int hCountSuits[];
   private JPanel buttonPanel;
   private JPanel buttonPanel2;
   private JPanel buttonPanel3;
   // private Image logo1;
   private GridBagLayout gbLayout;
   private GridBagConstraints gbConstraints;
   private Container container;
   
   public DeckOfCards()
   {
      super( "Card Dealing Program" );
 
      String faces[] = { "Ace", "Deuce", "Three", "Four",
                         "Five", "Six", "Seven", "Eight",
                         "Nine", "Ten", "Jack", "Queen",
                         "King" };
      String suits[] = { "Hearts", "Diamonds",
                         "Clubs", "Spades" };
 
	// set up counting arrays 
	//these will be used by comparing string values of the cards and then adding
	// one to their position in the array, can then analyze the array to 
	// determine what we have in our hands.  the suits array is for calculating flushes
 
	mCountFaces = new int[13];
	mCountSuits = new int[4];
	// his counting arrays
	hCountFaces = new int[13];
	hCountSuits = new int[4];
 
      deck = new Card[ 52 ];
	// hold MY cards
      myHand = new Card[ 5 ];
	// hold his cards
	hisHand = new Card[ 5 ];
 
	currentCard = -1;
 
      for ( int i = 0; i < deck.length; i++ )
         deck[ i ] = new Card( faces[ i % 13 ],
                               suits[ i / 13 ],i );
 
      container = getContentPane();
 	gbLayout = new GridBagLayout();
	container.setLayout( gbLayout );
 
	dealerTag.setText("Dealer" );
	playerTag.setText("Player 1");
	gbConstraints.fill = GridBagConstraints.BOTH;
	addComponent(dealerTag,1,3,1,1);
      	
      dealButton = new JButton( "Deal card" );
      dealButton.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               Card mDealt1 = dealCard();
		if ( mDealt1 != null ) {
                  mDisplayCard1.setText( mDealt1.toString() );
             		myHand[0] = mDealt1;
               }
		else {
                  mDisplayCard1.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
		Card hDealt1 = dealCard();
		if ( hDealt1 != null ) {
                  hDisplayCard1.setText( hDealt1.toString() );
             	hisHand[0] = hDealt1;
               }
		else {
                  hDisplayCard1.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
 
		   Card mDealt2 = dealCard();
		if ( mDealt2 != null ) {
                  mDisplayCard2.setText( mDealt2.toString() );
             		myHand[1] = mDealt2;
               }
		else {
                  mDisplayCard2.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
		Card hDealt2 = dealCard();
		if ( hDealt2 != null ) {
                  hDisplayCard2.setText( hDealt2.toString() );
             		hisHand[1] = hDealt2;
               }
		else {
                  hDisplayCard2.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
 
		   Card mDealt3 = dealCard();
		if ( mDealt3 != null ) {
                  mDisplayCard3.setText( mDealt3.toString() );
                       	myHand[2] = mDealt3;
			}
		else {
                  mDisplayCard3.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
		Card hDealt3 = dealCard();
		if ( hDealt3 != null ) {
                  hDisplayCard3.setText( hDealt3.toString() );
                       	hisHand[2] = hDealt3;
			}
		else {
                  hDisplayCard3.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
 
		   Card mDealt4 = dealCard();
		if ( mDealt4 != null ) {
                  mDisplayCard4.setText( mDealt4.toString() );
                      	myHand[3] = mDealt4;
			}
		else {
                  mDisplayCard4.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
		Card hDealt4 = dealCard();
		if ( hDealt4 != null ) {
                  hDisplayCard4.setText( hDealt4.toString() );
                      	hisHand[3] = hDealt4;
			}
		else {
                  hDisplayCard4.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
 
		   Card mDealt5 = dealCard();
		if ( mDealt5 != null ) {
                  mDisplayCard5.setText( mDealt5.toString() );
                      	myHand[4] = mDealt5;
			}
		else {
                  mDisplayCard5.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
		Card hDealt5 = dealCard();
		if ( hDealt5 != null ) {
                  hDisplayCard5.setText( hDealt5.toString() );
                      	hisHand[4] = hDealt5;
			}
		else {
                  hDisplayCard5.setText(
                     "NO MORE CARDS TO DEAL" );
                  status.setText(
                     "Shuffle cards to continue" );
               }
 
 
		// this is just a test to print out to the console
		for(int tempx = 0;tempx<5;tempx++){
			System.out.println(myHand[tempx].toString());
		}
		// this is just a test to print out to the console
		for(int tempy = 0;tempy<5;tempy++){
			System.out.println(hisHand[tempy].toString());
		}
 
            }
         }
      );
	dealButton.setEnabled(false);
      //c.add(dealButton);
	
 
	discardButton = new JButton( "Discard" );
	discardButton.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
              // put functionality for discard here 
			System.out.println("discarded");
		}
	   }
      );
	//c.add(discardButton);
 
 
      shuffleButton = new JButton( "Shuffle cards" );
      shuffleButton.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               mDisplayCard1.setText( "SHUFFLING ..." );
               shuffle();
               mDisplayCard1.setText( "DECK IS SHUFFLED" );
		   mDisplayCard2.setText( " " );
	         mDisplayCard3.setText( " " );
               mDisplayCard4.setText( " " );
               mDisplayCard5.setText( " " );
		   hDisplayCard1.setText( " " );
		   hDisplayCard2.setText( " " );
	         hDisplayCard3.setText( " " );
               hDisplayCard4.setText( " " );
               hDisplayCard5.setText( " " );
            }
         }
      );
      //c.add(shuffleButton);
		
      mDisplayCard1 = new JTextField( 15 );
      mDisplayCard1.setEditable( false );
      //c.add( mDisplayCard1);
	
	hDisplayCard1 = new JTextField( 15 );
      hDisplayCard1.setEditable( false );
      //c.add(hDisplayCard1);
 
	mDisplayCard2 = new JTextField( 15 );
      mDisplayCard2.setEditable( false );
      //c.add( mDisplayCard2);
	
	hDisplayCard2 = new JTextField( 15 );
      hDisplayCard2.setEditable( false );
      //c.add( hDisplayCard2);
	
	mDisplayCard3 = new JTextField( 15 );
      mDisplayCard3.setEditable( false );
      //c.add( mDisplayCard3  );
	
	hDisplayCard3 = new JTextField( 15 );
      hDisplayCard3.setEditable( false );
      //c.add( hDisplayCard3);
	
	mDisplayCard4 = new JTextField( 15 );
      mDisplayCard4.setEditable( false );
      //c.add( mDisplayCard4 );
	
	hDisplayCard4 = new JTextField( 15 );
      hDisplayCard4.setEditable( false );
      //c.add( hDisplayCard4);
	
	mDisplayCard5 = new JTextField( 15 );
      mDisplayCard5.setEditable( false );
      //c.add( mDisplayCard5);
	
	hDisplayCard5 = new JTextField( 15 );
      hDisplayCard5.setEditable( false );
      //c.add( hDisplayCard5);
	
      status = new JLabel();
      //c.add( status );
 
	setSize( 400,400);  // set the window size
      show();               // show the window
   }
 
   public void shuffle()
   {
      currentCard = -1;
 
      for ( int i = 0; i < deck.length; i++ ) {
         int j =  ( int ) ( Math.random() * 52 );
         Card temp = deck[ i ];   // swap
         deck[ i ] = deck[ j ];   // the
         deck[ j ] = temp;        // cards
      }
 
      dealButton.setEnabled( true );
   }
 
   public Card dealCard()
   {
      if ( ++currentCard < deck.length )
         return deck[ currentCard ];
	
      else {
         dealButton.setEnabled( false );
         return null;
      }
   }
 
   public void findOnePair(){}
 
   public void findTwoPair(){}
 
   public void findThreeOfAKind(){}
 
   public void findFourOfAKind(){}
 
   public void findFlush(){}
 
   public void findStraight(){}
 
   public void findFullhouse(){}
 
   
   private void addComponent(Component c, int row, int column, int width, int height){
 
	   gbConstraints.gridx = column;
	   gbConstraints.gridy = row;
 
	   gbConstraints.gridwidth = width;
	   gbConstraints.gridheight = height;
 
	   gbLayout.setConstraints(c,gbConstraints);
	   container.add(c);
 
   }
 
 
 
   public static void main( String args[] )
   {
      DeckOfCards app = new DeckOfCards();
 
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}
 
 
 
class Card {
   private String face;
   private String suit;
   private int rep;
 
   public Card( String f, String s, int r )
   {
      face = f;
      suit = s;
      rep = r;
   }
 
   public String toString() { return face + " of " + suit; }
}


Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

Re: Please assist with NullPointer error.... Posted: Jul 23, 2002 10:07 AM
Reply to this message Reply
Never mind, I figured out that I was trying to use a graphic object (gbConstraints) without instantiating it first... thanks anyway! I was just having problems with understanding JAVAC since it doesnt give good error info!

thomas

Posts: 42
Nickname: turbomanic
Registered: Jul, 2002

Re: Please assist with NullPointer error.... Posted: Jul 23, 2002 10:13 AM
Reply to this message Reply
From looking at your code you know alot about java so odds are this may not be the problem. I found from experience that most null pointer exceptions comes from not initializing objects. If you use an object that don't have an assigned value to it then it will cause a null pointer exception displayed even though it compiles. This is the hardest situation to find thats why I think that this may cause your exception. Check all objects and make sure that you don't use an object to call a method that hasn't been fully initialized. That's the only advice I can tell you hope it helps.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Please assist with NullPointer error.... Posted: Jul 23, 2002 11:25 AM
Reply to this message Reply
You guys are losing me in this discussion. Seems to me that the easiest solution is to look at the exception stack trace. More importantly, when you post a "why am I getting an XException" type of question, please include the stack trace.

For example, I could post this incredibly stimulating piece of software technology:
class Hello 
{
   String subject;
   Hello( String who )
   {
      subject = who;
   }
   
   String getGreeting()
   {
      return "Hello, " + subject + ".";
   }
   
   public static void main(String args[])
   {
      Hello friendlyObject = null;
      System.out.println( friendlyObject.getGreeting() );
   }
}
and say that there is a NullPointerExceptoin when I run it. Then, you'd be forced to pore over the source code for hours trying to find out why. Or I could be kinder and also include the output of the program:
Exception in thread "main" java.lang.NullPointerException
at Hello.main(Hello.java:16)

With this valuable information, you'd be able to spot the problem in a jiffy. What do you think the chances are it is somewhere in the neighborhood of line 16 in Hello.java?

Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

Re: Please assist with NullPointer error.... Posted: Jul 23, 2002 11:34 AM
Reply to this message Reply
Matt I really appreciate your feedback, at least to me, between you and SMETS, you guys provide the bulk of the best answers here. I simply did not include the stack for 2 reasons, first of all I didnt appreciate the value of it. I didnt understand how to read it when it is usually more than just the one line long. also, I assumed that since I included the complete source that you could do a cut/paste and compile it for yourself quite possibly using a better debugger... sorry for the inconvenience... by the way, I did figure this out, but could not pull the topic before i got responses. thanks anyway

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Please assist with NullPointer error.... Posted: Jul 23, 2002 12:33 PM
Reply to this message Reply
Sorry, I just can't resist the occasional opportunity to indulge in sarcasm. ;-)

Seriously, though, it is pretty common that people post code and say that there is some exception, but don't post the exception information. The copy/past option is time-consuming and doesn't often work (particularly when someone is using a particular environment like JBuilder or BlueJ that imports special packages).

That's why I wanted to emphasize the importance of that, not just for you, but for everyone posting questions.

Maybe we need a little "Posting Tips" list right at the top of the forum that suggests what information to include and also suggests using the "Formatting Your Post" tags. Those tags are described at the bottom of the page, where I think most people don't notice them.

Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

Re: Please assist with NullPointer error.... Posted: Jul 23, 2002 12:46 PM
Reply to this message Reply
well I most definitely got the hint! since I use DOS to compile my stuff still, it is not easy to get the stack info since I can't just copy it. but dont worry, that wont stop me now! :) I will figure something out!
thanks again for stopping by to look at my stuff. Obviously, I saw the tag stuff, but yes a general hints section authored mainly by the main people who do respond and know what they need to respond efficiently would be a very good idea. anyway, keep up the good work! L8R

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Please assist with NullPointer error.... Posted: Jul 23, 2002 1:48 PM
Reply to this message Reply
If you are compiling in a DOS box or "Command Prompt" in Windows, you can copy from it by clicking on the Window's icon on the upper left and selecting "Edit/Mark" (the particulars of this varies slightly depending upon the Windows version, but they all have it).

In an NT/Win2k/XP command shell, you can run your program like this: "java MyProg 2>output.txt" and that will redirect the error output to the output.txt file.

If you are really on DOS only it can be done, too, but we won't go into that, for the follwing reason: I doubt you are woking in real DOS, since Javac.exe is a Windows console application (I just did a hex dump of it to check) and only says "This program cannot be run in DOS mode" under DOS.

Flat View: This topic has 7 replies on 1 page
Topic: arrays and string......removing comma Previous Topic   Next Topic Topic: HOW DO I CREATE A JAR FILE?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use