kanglais
kanglais

Reputation: 73

Roll the Dice Assignment in Java: Calling a Method

I'm new to programming and am having trouble figuring out how to call methods once they're written in another part of the code. Below is a piece of the whole code (not everything!) but I'd really appreciate it if someone could not only correct this but sort of explain what I'm doing wrong? I'm taking an online class and the prof is a little difficult to get in touch with!

while (x == 'y'){

int roll = 1;

System.out.println("Roll " + roll);

roll++;

System.out.println(RollTheDice(dA, dB));
}

}

public static int RollTheDice(int dA, int dB){
    int A = (int)(Math.random() * 6 + 1);
    int B = (int)(Math.random() * 6 + 1);

    System.out.println(A + "\n" + B);

    int sum = (A + B);

    if (sum == 7)
        System.out.println("Craps!" + "\n");
    else if (sum == 2)
        System.out.println("Sanke eyes!" + "\n");
    else if (sum == 12)
        System.out.println("Box cars!" + "\n");

    return A + B; 

}

Upvotes: 0

Views: 604

Answers (2)

outis nihil
outis nihil

Reputation: 736

Well, to start with, you have a while loop with a condition while (x == 'y') - but you never change the value of x. The result of this is that the loop will never end (infinite loop).

Your next problem is that you don't define what dA and dB are in the calling context, only in the static function. Since the called function defines two parameters as ints, when you call it, you should be calling it as RollTheDice(5, 6) or you should assign int values to dA and dB (by the way, you know that when you are calling the function, the variables in the call do not have to have the same names as the variables in the function parameters, right?).

int xA = 5;
int xB = 6;
System.out.println(RollTheDice(xA, xB));

Finally, all this is assuming that there's a missing void Main() { line at the top.

Upvotes: 0

Wires77
Wires77

Reputation: 351

First of all, by declaring roll within the while loop, the value will forever be 1 or 2 because it will do that in each loop iteration. You need to declare that before the loop:

int roll = 1;
while(x == 'y') {
  roll++;
}

Next, your RollTheDice function doesn't do anything with the variables you pass to it (i.e. dA and dB are unused and A and B are used instead) so it doesn't matter what you pass in.

Finally, if you didn't declare dA and dB as variables above the while loop, the function call will fail. You need to pass actual values into the call like so:

RollTheDice(1, 6);

Upvotes: 2

Related Questions