954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Java Card Class Null error

//This is the error that i have Exception in thread "main" java.lang.NullPointerException
//at CardTest.main(CardTest.java:16)
/**
* @(#)CardTest.java
*
*
* @Robert Coughlin
* @version 1.00 2010/10/15
*/
//this is the main

public class CardTest {

public static void main(String [] args) {
Card [] randomCard=new Card[20];
for(int i= 0; i<20; i ++)
{
randomCard[i].flipCard();//this is the line that i get the error in
randomCard[i].getSuit();
}
for(int y= 0; y<20; y ++)
{
System.out.println(randomCard[y].toString());
}

}


}
/**
* @(#)Card.java
*
*
* @Robert Coughlin
* @version 1.00 2010/10/15
*/

import java.util.*;
public class Card {
private String Suit;
private int FaceValue;
public Card() {
Suit="";
FaceValue=0;
}

public int flipCard(){
Random randGen= new Random( );
FaceValue= randGen.nextInt(11)+1;
return FaceValue;
}//ends flipCard

public String getSuit(){
int value = 0;
Random randGen= new Random( );
value= randGen.nextInt(4)+1;
System.out.println(value);//oputs value of random number
if(value==1)
Suit="Spades";
if(value==2)
Suit="Diamonds";
if(value==3)
Suit="Hearts";
if(value==4)
Suit="Clubs";
return Suit;
}//ends getSuit

public String toString(){
String str;
str="Face Value: " + FaceValue +"\n"
+ "Suit: " + Suit;
return str;
}//ends toString
}//ends class

rcogq7
Newbie Poster
2 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

Constructing an array of objects in java is a 2 step process. First you create the array of references. Then you must construct the actual objects. You have skipped the second step. You only have an array of references, but the references don't point to actual objects. You can not call a method on a reference that doesn't refer to an object.

Please post your code inside code tags next time.

kramerd
Posting Pro in Training
403 posts since Sep 2010
Reputation Points: 49
Solved Threads: 73
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: