Can somebody please help me with this example? Thanks
"Has three methods (beside main): Void method “showMenu” that displays the following:
Rock = 1
Paper = 2
Scissors = 3
Int method “computerChoice” that uses “Random” to randomly generate a number between 1 to 3
Char method “findWinner” that accepts the user choice and the computer choice and by checking the numbers
So if user said 1 and computer 2 => computer is the winner
If user said 1 and computer 3 => user wins
If user said 2 and computer 3 => computer wins
If both of the same number (e.g. 1 and 1 or 2 and 2 or 3 and 3) then it is tie
Main method:
In the main method you do the following:
You need to ask the user to enter their choice as an integer so you need a variable for that.
Also the method computerChoice returns an integer and you need to save that too
Then send the two choices to the method “findWinner” and once you find a who is the winner you will either return ‘c’ for computer or ‘u’ for the user
Then you should check the c or u and display the winner based on that
All of these is happening within a while loop (logical one); therefore you need a flag for that as well
The job of this outer while loop is to check if the user wants to play again or not. If yes that means the flag is “STILL” true and you would again play and if not the flag becomes false and that terminates the loop and therefore terminates the program.
How to do the game:
Inside the while loop of the main method (the one explained above):
First call the “showMenu” method to display the menu
Then ask the user to select a number based on the menu
Capture the user selection
Then call the computerChoice method and store the randomly generated value that is returned
Then call the findWinner method by passing the two arguments to the method and return either ‘c’ or ‘u’.
Then based on the return of the findWinner method display to the user that who won
Then ask them do they want to continue or not
For that you need another variable to store an integer of 0 or 1
If 0 flag is false and you will end the program
If 1 flag is true (still) and you would continue
Hint: You need to important java.util.Scanner and java.util.Random
And you need to provide the following before the main method:
Random rand = new Random();
Also you method headers are like (be careful about case sensitivity – public or private are lower case)
Public static void main(String[] args) { }
Private static void showMenu() {}
Private static int computerChoice() {}
Private static char findWinner (int userChoice, int computerChoice) {} "
Aucun commentaire:
Enregistrer un commentaire