0
//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

Edited by mike_2000_17: Fixed formatting

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by kramerd
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.

Edited by kramerd: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.