为什么这些行被跳过? (JAVA)
问题描述:
这里的源代码的相关位:为什么这些行被跳过? (JAVA)
class Dice
{
String name ;
int x ;
int[] sum ;
...
public Dice (String name)
{
this.name = name ;
this.x = 0 ;
this.sum = new int[7] ;
}
...
public static void main (String[] arg)
{
Dice a1 = new Dice ("a1") ;
printValues (a1) ;
}
public static void printDice (Dice Dice)
{
System.out.println (Dice.name) ;
System.out.println ("value: "+Dice.x) ;
printValues (Dice) ;
}
public static void printValues (Dice Dice)
{
for (int i = 0; i<Dice.sum.length; i++)
System.out.println ("#of "+i+"'s: "+Dice.sum[i]) ;
}
}
这里是输出:
#of 0's: 0
#of 1's: 0
#of 2's: 0
#of 3's: 0
#of 4's: 0
#of 5's: 0
#of 6's: 0
为什么没有这两条线执行内部printDice
:
System.out.println (Dice.name) ;
System.out.println ("value: "+Dice.x) ;
,如果他们的话,我希望能看到“A1”和“价值:0” #of
的
答
printDice()
从未被称为:
public static void main (String[] arg)
{
Dice a1 = new Dice ("a1") ;
printValues (a1) ; // You only call printValues
}
答
可能因为您发布的任何代码实际上都没有调用printDice()
。
除main()
方法外,您的类中没有任何方法会被魔法调用 - 它们需要由其他代码调用。
+0
哇。严。那会做。我非常想念事情。 – David 2010-04-14 20:20:45
答
要调用函数printValues,你大概的意思打电话给printDice。
答
我不是Java大师,但我认为您最好避免以与您命名类相同的方式命名参数。当你写:
public static void printDice (Dice Dice) { /* ... */ }
你走在薄冰,伙计。读你的代码很难知道你是否调用静态方法或实例。我不得不承认,我对Java允许类似的东西感到惊讶,因为它在阅读时似乎非常危险且难以理解。在空闲时间 - 而不是编码 - 读一些鲍勃叔叔的文本;)和平!
对于这类事情来说,一个好的策略是从一开始就逐步完成代码,并手工跟踪代码,确保去代码所在的位置,而不是代码所在的位置。 – 2010-04-14 20:23:30
你不应该像类那样命名变量,因为'Dice.name'看起来像你想访问Dice类的静态字段'name',但实际上你想访问对象的字段。请参阅http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html – Progman 2010-04-14 20:24:17