开发者

Why are these lines being skipped? (java)

开发者 https://www.devze.com 2022-12-27 02:45 出处:网络
Here\'s the relevant bit of the source code: class Dice { String name ; int x ; int[] sum ; ... public Dice (String name)

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 row开发者_运维技巧s of #of's


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() is never called:

public static void main (String[] arg) 
{
    Dice a1 = new Dice ("a1") ; 
    printValues (a1) ; // You only call printValues
}


You are calling printValues where you probably mean to call printDice.


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:

public static void printDice (Dice Dice) { /* ... */ }

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消