Hey guys, im just learning how to use methods but I really cant seem to understand them.

We have a question where we have to write a program for the following game.

There is a little known dice game which is played with a pair of dice and has the following rules: the player keeps rolling the dice until the total on the dice is 2, 3, 7, 11 or 12. If the total is 7, then the player loses, if it's 2, 3, 11 or 12 then the player wins. If the total is any other number, then the game continues.

Im really stuck in the mud as I have no idea how to write a method that will only return if the values match the ones above.

Any help would be great!

Thank you
David

Code so far below

``````public class DiceGame
{
static int random(int low, int high)
{
int random = (int)(Math.random() * (high - low) +  low + 1);
return random;

}

public static void main(String args [])
{

System.out.println("Would you like to play the game? (y/n) ");

char response = responseLine.charAt(0);

if(response == 'y')
{
for(int i = 0; i <= 10; i ++)
{
int low = 1;
int high = 6;
System.out.println("The dice are cast young one ");
System.out.println("The total is: ");
System.out.println(random(low,high) + random(low,high));
}
}

}
}
``````

First of all, I think you better use the Random class rather the `Math.random()`. If you want the game to continue until a certain condition is true, you can use the while …

What apines said is correct, but if you want to use methods, you can write boolean methods that will test if the diceSum has one of the values you are interested in. For example,

``````private boolean playerWins(int diceSum) {
return diceSum == 2 || diceSum == 3 …``````

This is not the correct usage of a while loop - your code will return true if the dice sum is indeed 2,3,7,11 or 12 but will be stuck in an infinite loop otherwise because you do not change the value of diceSum inside the loop. After reading again the …

The error is because the line

``if(PlayerWins)``

States that if the variable PlayerWins is true, execute the code block. What we want is

``if(PlayerWins(diceSum))``

Which means if the method PlayerWins is true when passing to it the argument diceSum. The compiler doesn't know what …

## All 15 Replies

First of all, I think you better use the Random class rather the `Math.random()`. If you want the game to continue until a certain condition is true, you can use the while loop:

``````while(expression)
{
//do something
}
``````

As long as the expression is true, the loop will continue. In your case, you want the expression to be true if the dice are not 2,3,7,11 or 12.

``````int diceSum = dice1 + dice2; //This will hold the sum of both dice tosses.
while(diceSum != 2 && diceSum != 3 && diceSum != 7 && diceSum !=11 && diceSum != 12)
{
//do something
}
``````

Try to work with this code, and if you encounter any problems post your new code here and we'll help you out :) (Please use the (code) button when posting code)

What apines said is correct, but if you want to use methods, you can write boolean methods that will test if the diceSum has one of the values you are interested in. For example,

``````private boolean playerWins(int diceSum) {
return diceSum == 2 || diceSum == 3 || diceSum == 11 || diceSum == 12;
}

private boolean playerLoses(diceSum) {
return diceSum == 7;
}``````

Can you figure out how to incorporate methods like this into your code?

First of all, I think you better use the Random class rather the Math.random(). If you want the game to continue until a certain condition is true, you can use the while loop:

``````while(expression)
{
//do something
}
``````

As long as the expression is true, the loop will continue. In your case, you want the expression to be true if the dice are not 2,3,7,11 or 12.

``````int diceSum = dice1 + dice2; //This will hold the sum of both dice tosses.
while(diceSum != 2 && diceSum != 3 && diceSum != 7 && diceSum !=11 && diceSum != 12)
{
//do something
}
``````

Try to work with this code, and if you encounter any problems post your new code here and we'll help you out :) (Please use the (code) button when posting code)

First off thank you so much for the help :)

Second I understand your idea about using a while loop I think, Basically it looks like im trying to return a true value if the statement is equal to the numbers given i.e. the player wins if the dice is equal to 2 but loses if its equal to 7(7 is the only condition where the player loses btw).

So far with the ideas you gave me this is what Ive developed for my method, ignore the bottom part of the code(its just a for loop to play the game 10 times)

``````public class DiceGame
{
static int random(int die1, int die2)
{

die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;

int diceSum = die1 + die2;

while(diceSum == 2 && diceSum == 3 && diceSum == 7 && diceSum == 11 && diceSum == 12)
{
return(true);
}

}

public static void main(String args [])
{

System.out.println("Would you like to play the game? (y/n) ");

char response = responseLine.charAt(0);

if(response == 'y')
{
for(int i = 0; i <= 10; i ++)
{

System.out.print("blah");

}
}

}
}
``````

Thank you again for the help
David

This is not the correct usage of a while loop - your code will return true if the dice sum is indeed 2,3,7,11 or 12 but will be stuck in an infinite loop otherwise because you do not change the value of diceSum inside the loop. After reading again the problem, I believe that kramerd's idea is better and will give you the usage of methods that you wanted. Define a method isPlayerWins

``````private boolean isPlayerWins(int diceSum) {
return diceSum == 2 || diceSum == 3 || diceSum == 11 || diceSum == 12;
}``````

This method will return true if the player wins, false otherwise. Now, what you need is

``````public static void main(String args [])
{
System.out.println("Would you like to play the game? (y/n) ");
char response = responseLine.charAt(0);
if(response == 'y')
{
int diceSum = random(1, 6) + random(1,6) //you need to complete this method that returns the dice throw.
for(int i = 0; i <= 10; i ++)
{
// using the isPlayerWins(diceSum) method, you need to determine whether the player won or lost.
}
}
}``````

Try to implement the code using this new information, good luck :)

Ok so what Ive come up with using the method you gave me is

``````public class DiceGame
{
static int random(int die1, int die2)
{

die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;

}

public boolean PlayerWins(int diceSum)
{
return diceSum == 2 || diceSum == 3 || diceSum == 11 || diceSum == 12;
}

public static void main(String args [])
{

System.out.println("Would you like to play the game? (y/n) ");

char response = responseLine.charAt(0);

if(response == 'y')
{

int diceSum = random(1, 6) + random(1,6);

for(int i = 0; i <= 10; i ++)

{

if(PlayerWins)
{
System.out.print("Winner");
}
else
System.out.println("Loser");

}

}

}

}``````

The problem is it wont compile because it cannot find the PlayerWins variable but I dont know how to declare it again.

And I was wondering if I could ask you, when using a method how do you know what you want to return?

Thank you again for all your help and putting up with my n00bish failures:P

The error is because the line

``if(PlayerWins)``

States that if the variable PlayerWins is true, execute the code block. What we want is

``if(PlayerWins(diceSum))``

Which means if the method PlayerWins is true when passing to it the argument diceSum. The compiler doesn't know what is the variable PlayerWins only the method, so it returns an error.

I am not sure that I understood your second question, can you explain?

My new if statement is

``````for(int i = 0; i <= 10; i ++)

{

if(PlyerWins(int diceSum))
System.out.print("Winner");

}``````

But now Im getting two compiler errors and one Ive never seen before,

``````DiceGame.java:36: '.class' expected
if(PlyerWins(int diceSum))
^
DiceGame.java:36: illegal start of expression
if(PlyerWins(int diceSum))
^``````

And sorry for not explaining that question better, let me try again.

What I ment was that when you write a method you use the return statement to return a value, what I dont understand is then later on in your code what part of the method do you use to call for that value you returned i.e. do you use the method name, the parameter name or the actual return name?

Thanks again:)

ok, let's review methods a little bit :) When creating a method, the syntax is:

``<visibility> <optional static> <return type> methodName(<optional parameters>)``

For example, let's consider the most famous method

``public static void main(String[] args)``

The visibility is the public keyword, it is static (if you don't know what static is, ask and I will elaborate). Its return type is void, which means it does not return anything, the name of the method is main and it accepts one String array argument named args. Notice that in the method declaration, we put the type of each parameter before its name - we indicate that args is String[].

If we wanted to create a public, not-static method which returns an int, called myMethod and accepts two parameters - one double named doubleVar and a char named charVar, we would have written:

``public int myMethod(double doubleVar, char charVar)``

Again, we indicate that doubleVar is double and charVar is char.

Now, we want to call this method from another method. The syntax for it is simple:

``methodName(<optional arguments>)``

Let's say that we want to call myMethod from the main method, the syntax would be:

``````public static void main(String args[])
{
double dVar = 4.564;
char hello = 'c';
myMethod(dVar, hello);
}``````

Notice that this time we didn't need to specify the type (we didn't write myMethod(double dvar, char hello)) - the type that needs to be sent to the method is known to the compiler from the method declaration, and if you pass parameters of different type, the compiler will shout at you.

One last thing, we have created the myMethod to return an int, so we can use it and store the returning value of the method in a variable:

``````public static void main(String args[])
{
double dVar = 4.564;
char hello = 'c';
int returnValue;
returnValue = myMethod(dVar, hello); //now returnValue will store the value that myMethod returned.
}``````

Now - can you spot errors in your code? :)

Sorry for the late reply, life has been crazy the last few days so im only getting to look at my code now.

After reading your information on methods it seems like what I was doing wrong was including the wrong parameter types so now Ive tried this

``````public class DiceGame
{
static int random(int die1, int die2)
{

die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;

}

public boolean PlayerWins(int diceSum)
{
return diceSum == 2 || diceSum == 3 || diceSum == 11 || diceSum == 12;
}

public static void main(String args [])
{

System.out.println("Would you like to play the game? (y/n) ");

char response = responseLine.charAt(0);

if(response == 'y')
{

int diceSum = random(1, 6) + random(1,6);

for(int i = 0; i <= 10; i ++)

{

if(PlyerWins(diceSum))
System.out.print("Winner");

}

}

}

}``````

But im still getting complier errors :(

Im totally frustrated because I just cant seem to understand how to write a method and so im really thankful for all the help your giving me:)

My guess is that your compiler errors are from not recognizing Console.readString() - I am not familiar with that method in the Console class. Second thing is that your method is called PlayerWins but you are invoking on line 37 PlyerWins.

Are there any other compiler errors?

No there is only the one error and here it is

``````DiceGame.java:34: cannot find symbol
symbol  : method PlyerWins(int)
location: class DiceGame
if(PlyerWins(diceSum))
^
1 error``````

The method is `PlayerWins(diceSum)` - but you are calling `PlyerWins(diceSum)` .

FYI - the Java naming conventions encourage methods and variables to start with a lowercase letter, and classes with an uppercase letter.

Ok Ive fixed that error, now though its telling me that Im missing a bracket at line 11 except I do have a bracket there.

Any ideas what I might be doing wrong?

``````DiceGame.java:11: missing return statement
}
^
1 error``````

``````static int random(int die1, int die2)
{
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
}``````

From the header `static int random(int die1, int die2` ) we know that the method takes two int parameters, die1 and die2, and returns an int. This is not exactly what you want, right? You want the method to simply return a number that will represent the sum of the two die throws. Meaning you want the method to return an int, but you don't need any parameters sent to it. We should write:

``````static int random()
{
int die1 = (int)(Math.random()*6) + 1;
int die2 = (int)(Math.random()*6) + 1;
}``````

Now, this method computes two int random values, but doesn't do nothing with them - we need to explicitly tell the method what we want to return. Since you stated the int in "static int random", the compiler will shout at you if you won't return an int in the end of your method. We need to use the return keyword in order to return a value from the method. We said that we want to return the sum of the two die throws, so we can write:

``````static int random()
{
int die1 = (int)(Math.random()*6) + 1;
int die2 = (int)(Math.random()*6) + 1;
int dieSum = die1 + die2; //calculating the sum
return dieSum;  //returning the sum;
}``````

Or, in the same way, we can simply write:

``````static int random()
{
int die1 = (int)(Math.random()*6) + 1;
int die2 = (int)(Math.random()*6) + 1;
return die1 + die2;  //the value die1 + die2 will be calculated and returned.
}``````

Don't worry, you will get the syntax and usage of methods in no time :)

Thanks for all the help man.

Ive been at it all day but I finally managed to crack it with your help.

Here is what I came up with if your interested:)

``````public class DiceGame
{

// This program was developed to run a simple dice game in whice the user would win if he retained a certian randomly generated number from a set of dice and similary lose if he retained a certian number i.e. 7
// This program was written by David O'Regan, Student number : 10331017.  15/11/2010

//This program was tested in terminal at length by myself to ensure its working order.

static int random()// First I designed a method that would generate a random number between 1 and 6.
{

int die1 = (int)(Math.random()*6) + 1;

return die1;

}

static boolean playerWins(int diceSum)// I then created a method that would return a boolean if the sum of two of my random numbers i.e. two dice were equal to the winning numbers.
{
return diceSum == 2 || diceSum == 3 || diceSum == 11 || diceSum == 12;
}

static boolean playerLoses(int diceSum)// This method is the exact same as the one above it, save this method is true when the sum of the two dice equals the losing number i.e. 7
{
return diceSum == 7;
}

public static void main(String args [])
{

while(true)// I placed my code into a while loop so that it would continue to run until it came upon the winning or losing statement.
{

System.out.println("Would you like to play the game? (y/n) ");

char response = responseLine.charAt(0);

if(response == 'y')
{

int dice1 = random();
int dice2 = random();// I created two variables so that the two numbers would stay the same and not regenerate.

int diceSum = dice1 + dice2;// using the variables I added the two random numbers(note, it was important that I use the above variables or my two numbers would not be the same as my sum i.e. two new numbers would have been generated if I used random().

System.out.println("The Dice are ");
System.out.println(dice1 + "\t" + dice2);

System.out.println("The total is " + diceSum);

if(playerWins(diceSum))
{
System.out.print("Yay, you are a Weener!..... wait I ment Winner :)");
break;// I set my while loop to break if it came upon this statement or the one below it, this effectively ends the loop/game if the player generates the winning or losing number.
}

if(playerLoses(diceSum))
{
System.out.println("Sorry dude you lost:( but dont worry cause lifes still awesome:)");
break;
}

}
}
}

}``````

Hopefully this code might help someone else down the line:)

Thanks again dude, I wouldn't have ever gotten my head around methods with out ya

David

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.