2013-10-11 102 views
3

我有下面的代码,并且想知道为什么当我运行该程序时返回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; 
    } 


} 
+4

你永远不叫'卡()'.. –

+0

String的缺省值为空。你从来没有初始化字符串的任何值 – newuser

+1

我认为调试的第一步是学习在每个方法中添加System.out.println以逐块跟踪方法 – Jianhong

回答

5

因为空在程序运行时所值保存的值。

在拨打getCard()之前,如果您没有拨打任何有价值的参考方法(如card()),为什么它会有所不同?

这里的关键是尝试通过智力来逐步了解您的代码,以了解它的功能。或者用调试器遍历代码。

1

您打电话给getcard(),但从不打电话给card(),所以value从不设置。

0

应该叫card()功能:

public static void main(String[] args) { 
     card(); 
     System.out.println(getcard()); 
} 
1

检查你的代码的以下部分:

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

调用getcard(前),你需要调用卡()来准备你的计算。

您的代码需要如下所示。

public static void main(String[] args) { 
     card(); 
     System.out.println(getcard()); 
} 
0

你也可以有代码在你TestCard静态块将初始化value为您提供:

static{ 
    card(); 
} 

,让你知道价值是不可空

相关问题