我有以下代码,我想知道为什么运行程序时返回null而不是实际值?任何帮助都会被证实.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
因为null 是程序运行时值所持有的值.
如果你没有调用任何给出引用值的方法,例如card()在调用之前,为什么它应该是不同的getCard()?
这里的关键是尝试在心理上逐步完成代码,看看它的作用.使用调试器执行代码或执行代码.