Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why null is returned instead of a value?

Tags:

java

random

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;
    }


}
like image 572
NerdsRaisedHand Avatar asked Jan 23 '26 13:01

NerdsRaisedHand


1 Answers

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.

like image 81
Hovercraft Full Of Eels Avatar answered Jan 26 '26 03:01

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!