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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With