Reputation: 331
I have the following code, and am wondering why null is returned when I run the program and not the actual value? Any help would be appericated.
import java.util.Random;
public class TestCard {
public static String[] possCards = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
public static String[] possSuits = new String[]{"C", "S", "H", "D"};
public static Random rand = new Random();
static String value;
public static void main(String[] args) {
System.out.println(getcard());
}
public static void card() {
String card = possCards[rand.nextInt(possCards.length)];
String suit = possSuits[rand.nextInt(possSuits.length)];
value = card + suit;
}
public static String getcard(){
return value;
}
}
Upvotes: 3
Views: 96
Reputation: 3650
you could also have a static block of code in your TestCard
that will initialize the value
for you:
static{
card();
}
so you know value to be non null
Upvotes: 0
Reputation: 26094
Before calling the getcard() you need to call card() to preparing your calculations.
Your code need to look like below.
public static void main(String[] args) {
card();
System.out.println(getcard());
}
Upvotes: 0
Reputation: 15408
Check the following portion of your code:
public static void main(String[] args) {
System.out.println(getcard()); // printing getCard(),
//but card() isn't called before it!!
}
public static void card() {
String card = possCards[rand.nextInt(possCards.length)];
String suit = possSuits[rand.nextInt(possSuits.length)];
value = card + suit; // assigning value in card()
//but this function needs to get executed
}
Upvotes: 1
Reputation: 18675
You should call the card()
function:
public static void main(String[] args) {
card();
System.out.println(getcard());
}
Upvotes: 0
Reputation: 1553
You're calling getcard()
but never calling card()
, so value
is never set.
Upvotes: 1
Reputation: 285403
Because null is the value held by value at the time the program is run.
Why should it be any different if you don't call any of the methods that give value a reference, such as card()
, before calling getCard()
?
Key thing here is to try to walk through your code mentally step wise to see what it does. Either that or step through your code with a debugger.
Upvotes: 5