为什么要跳过这些行? (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”并在 #of
行的顶部打印“Value: 0”
Here's the relevant bit of the source code:
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]) ;
}
}
Here is the output:
#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
Why didn't these two lines execute inside printDice
:
System.out.println (Dice.name) ;
System.out.println ("value: "+Dice.x) ;
if they had then i would expect to see "a1" and "Value: 0" printed at the top of the rows of #of
's
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能是因为您发布的代码实际上都没有调用
printDice()
。除了
main()
方法之外,类中的任何方法都不会被神奇地调用 - 它们需要由其他代码调用。Probably because none of the code you posted actually calls
printDice()
.With the exception of the
main()
method, none of your methods in your classes are magically invoked - they need to be invoked by some other code.printDice()
永远不会被调用:printDice()
is never called:您正在调用 printValues,而您可能想调用 printDice。
You are calling printValues where you probably mean to call printDice.
我不是Java大师,但我认为你最好避免像命名类一样命名参数。当你写道:
你如履薄冰,伙计。阅读您的代码很难知道您是调用静态方法还是实例方法。我不得不承认,我很惊讶 Java 允许这样的事情,因为它在阅读时似乎非常危险且难以理解。在空闲时间 - 当不编码时 - 阅读一些鲍勃叔叔的文本;)和平!
I'm not a Java master, but I think that you'd better avoid naming the parameters the same way as you name a class. When you write:
you're walking on the thin ice, dude. Reading your code it's hard to know if you call the static methods or the instance ones. I have to admit that i was surprised that Java allows something like that as it seems to be very dangerous and hard to understand when reading. In a free time - while not coding - read some Uncle Bob's texts ;) Peace!