i am making a rock paper scissors game in java for collage and was wondering how to subtract 1 from a for loop.
the full code works but if some one enters a invalid number (lower then 1 or higher then 3) my code asks them to reenter a number(1, 2, 3)
but the for loop counts it as a loop so i end up with less moves.
i need to change something in the last "else if" but i cant figure it out
could some one point me in the right direction?
thanks.
the full code is this:
import java.io.*;
import java.util.Random;
public class RockPaperScissors {
static int loss = 0;
static int win = 0;
static int tie = 0;
int draw;
static int playerHand;
static int compHand;
int gameLoop;
public void playerMoves() {
if ( playerHand == compHand ){ //if both hands (player and computer) are the same
System.out.println("Draw, your picked " + playerHand + " and the computer picked " + compHand );
tie++; // add 1 to tie score
}
else if (playerHand == 1 && compHand == 2){ // if player picks Rock and computer picks paper
System.out.println("the computer picks " + compHand + "! " + "Paper beats rock, You lose");
loss++; // add 1 to loss score
}
else if (playerHand == 1 && compHand == 3){ // if player picks rock and computer scissors
System.out.println("the computer picks " + compHand + "! " + "Rock beats Scissors, You win!");
win++; // add 1 to win score
}
else if (playerHand == 2 && compHand == 1){ //if player picks paper and computer picks rock
System.out.println("the computer picks " + compHand + "! " + "Paper beats rock, you win!");
win++; // add 1 to win score
}
else if (playerHand == 2 && compHand == 3){ // if player picks paper and computer scissors
System.out.println("the computer picks " + compHand + "! " + "Scissors beats Paper, you lose!");
loss++; // add 1 to loss score
}
else if (playerHand == 3 && compHand == 1){ // if player picks scissors and computer rock
System.out.println("the computer picks " + compHand + "! " + "Rock beats Scissors, you lose!");
loss++; // add 1 to loss score
}
else if (playerHand == 3 && compHand == 2){ // if player picks scissors and computer paper
System.out.println("the computer picks " + compHand + "! " + "Scissors beats Paper, you win!");
win++; // add 1 to win score
}
else if (playerHand < 1 || playerHand > 3) {
System.out.println(playerHand + " is not a valid number. Try again...");// if not valid number ask again.
gameLoop = gameLoop - 1; // subtract 1 from gameLoop
}
else {
System.out.println("Great job, you broke it...");
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Welcome to Rock Paper Scissors");
System.out.println("Lets play ten games and see if you can outsmart the computer!");
for (int gameLoop = 0; gameLoop < 10; gameLoop++) { // a for loop to keep the game running 10 times
Random randomNumber = new Random(); // create a new random number everytime
compHand = (int) randomNumber.nextInt(3); // generate a random number for the computer (compHand)
compHand++;
// while (playerHand < 1 || playerHand > 3) {
// System.out.println(playerHand + " is not a valid move. Try again...");
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors draw = new RockPaperScissors();
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
draw.playerMoves(); // go to public void playerMoves and use that.
System.out.println("the score is: " + win + " Games won. " + loss + " Games lost. " + tie + " Games tie."); // print out the game score at the end of every game
System.out.println("");
}
}
}
It is a scope issue. You are declaring a new variable gameLoop in your for loop, which hides the variable gameLoop that has been declared at the beginning of your class.
public class RockPaperScissors {
...
int gameLoop; // 1. variable with name gameLoop declared
...
// 2. variable with name gameLoop declared; hides 1. declaration
for (int gameLoop = 0; gameLoop < 10; gameLoop++) {
^ this is not the same variable as above
A quick and easy solution would be to just omit the 'int' in the for-loop:
for (gameLoop = 0; gameLoop < 10; gameLoop++) {
Now, when you decrement it in the else-branch of your playerMoves() method, it should be noticed by the for-loop.
You could look towards keeping that while loop in main which checks if the playerHand is < 1 or > 3, and inside it, validate until the user inputs a valid number. The
below is a sample idea of what you can look towards doing. It is not perfect.
//Taking in the first input
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors draw = new RockPaperScissors();
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
//Validating the input repeatedly until it is valid
while (playerHand < 1 || playerHand > 3) {
System.out.println(playerHand + " is not a valid move. Try again...");
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
}
//Continue with your program
draw.playerMoves(); // go to public void playerMoves and use that.
I personally find validating here to be more convenient than validating in the playerMoves method, which is a bit long already as it is.
Alternatively, if you want to subtract the invalid guess from the for loop, you can do a gameLoop-- in the for loop for invalid guesses (and not execute the method by doing something like a continue after decrementing gameLoop).
Related
Create a program named rockPaperScissors.java
The program should validate user input.
Game should ask the user to play again and continue if yes and stop if no.
Once the user stops playing, program should print the total number of wins for the computer and
for the user.
I am trying to learn programming from a book, so I am not good at this. I need to return the values of Cwin and Uwin to the main method, but I know how to return one value to it. I also have a problem with looping the question. I cannot use arrays and could only use the basic while loops (without the (true) and break).
import java.util.*;
public class rockPaperScissors
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Play again? Type yes or no.");
String YoN= input.next();
if (YoN.equalsIgnoreCase("yes"))
{
game();
}
else
{
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static void game()
{
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
Random r = new Random();
int choice = console.nextInt();
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int result = -1;
if (choice > 1 || choice < 3)
{
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
int comp = r.nextInt(3) + 1;
if (comp == 1)
{
System.out.println("Computer chose rock.");
}
if (comp == 2)
{
System.out.println("Computer chose paper.");
}
if (comp == 3)
{
System.out.println("Computer chose scissors.");
}
if (choice == 1 && result == 2)
{
Cwin++;
}
if (choice == 2 && result == 3)
{
Cwin++;
}
if (choice == 3 && result == 1)
{
Cwin++;
}
if (choice == 2 && result == 1)
{
Uwin++;
}
if (choice == 3 && result == 2)
{
Uwin++;
}
if (choice == 1 && result == 3)
{
Uwin++;
}
}
}
If you want to return multiple values from a method you may use an array that stores the values in its elements. Check here.
However for this program there is no need for returning 2 values(and you also said "I cannot use arrays"). Instead you can have 2 global variables that record the number of times the player wins and the number of times the computer wins respectively. Lets call them playerWinCount and computerWinCount.
Now that we got that down, lets look at how we allow the user to replay the game. You say that can use only "basic while loops". Fine. What we do is we declare a variable choice that holds the user's entry when prompted to replay. We initialise choice to true and then keep asking the user if he'd like to play again until he decides not to.
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
The playGame() method has the code to play the game.
The way we validate the user's entry is by using a length check. If the entry is out of range(i.e. from 1 to 3 inclusive) he'll be prompted to enter again.
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
Having acquired a valid user input, the next thing we do is get a random number as the computer's pick(you've done that). Then we check who won the game and increment the number of times the winner has won. We can do this using a number of if statements like this:
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
Or we can just combine the 3 conditions of winning with the OR operator(||) and use just 2 if statements:
if(playerPick != computerPick)
{
if((playerPick == 1 && computerPick == 3) || (playerPick == 3 && computerPick == 2) || (playerPick == 2 && computerPick == 1))
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else
{
computerWinCount++ ;
System.out.println("Computer won!");
}
}
else
{
System.out.println("It's a tie!");
}
And that's about it.
Here's the entire code:
import java.util.* ;
public class RockPaperScissors
{
static Scanner scanner = new Scanner(System.in) ;
static int playerWinCount, computerWinCount ;
public static void main(String[] args)
{
playerWinCount = 0 ;
computerWinCount = 0 ;
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
System.out.println("\nNumber of times you won: " + playerWinCount) ;
System.out.println("Number of times computer won: " + computerWinCount) ;
System.out.println("Goodbye!") ;
}
public static void playGame()
{
System.out.println("") ;
Random random = new Random() ;
int playerPick = -1 ;
int computerPick = -1 ;
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
computerPick = random.nextInt(3) + 1 ;
System.out.println("The computer picked " + computerPick) ;
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
}
}
Let's go point by point.
You aren't taking the user input for determining the choice of playing in a while loop, so your game won't run more than once. You can take that input as:
while (true) {
System.out.println("Play again? Type yes or no.");
String YoN= input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game():
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
break;
}
}
If user gives input other than yes, you're trying to print Cwin and Uwin, but you haven't declared those variables in the scope of main method. So your program won't compile anyways.
You can keep global variables in the class running main method.
public static int Cwin = 0;
public static int Uwin = 0;
Update
I've gone through your code and found a few more problems. As far as I understand, you want to receive choice input from user and validate it in this segment:
if (choice > 1 || choice < 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
Well, this condition doesn't supports what you've printed inside, this choice > 1 || choice < 3 condition always gets true. Also, you haven't prompted to take the entry from the user again.
You can fix this issue as below:
while (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
choice = console.nextInt();
}
Then you're trying to make random choices for Computer. But you're selecting through upper bound and adding 1 to it. Why not set the bound to 1 more?
int comp = r.nextInt(4);
Then, finally, you're trying to compare the choice and the result. Where result was assigned -1 at the time of declaration and was never changed. That's why it'll never enter any if blocks and the Cwin and Uwin will always print 0. I bet you wanted comp here, in place of result. Also, I've tried to make the program more understandable to user while running.
if (choice == 1 && comp == 2) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 3) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 3 && comp == 1) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 1) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 3 && comp == 2) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 1 && comp == 3) {
Uwin++;
System.out.println("You win!");
return;
}
System.out.println("It's a draw!");
It will work as expected if you fix the aforementioned issues.
Note: I haven't refactored your code, I've just pointed out the problems and fixed it without modifying it much. It can be made lot more better than the current condition. Let's keep the topic for another day's question.
I modify your code somewhat.
You mention in a comment that you don't want to use an array and static variable.
so, I tried some different method hope It will help you.
It is fully working code
import java.util.*;
public class rockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome To Rock Paper scissors Game Type yes to continue or no for close.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game();
} else if(YoN.equalsIgnoreCase("yes")) {
System.out.println("Thank You");
}else {
System.out.println("Enter valid input");
}
}
public static void game() {
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int tie = 0;//Tie count
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Are you sure!!! Want to continue? Type yes or no.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
Scanner console = new Scanner(System.in);
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
int choice = console.nextInt();
int result = (int) (Math.random()*(3-1)) + 1;
if (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
if((choice == 1 && result == 3) || (choice == 2 && result == 1) || (choice == 3 && result == 2)) {
System.out.println("Computer Choose"+result);
Uwin++;
}else if((choice == 1 && result == 2) || (choice == 2 && result == 3) || (choice == 3 && result == 1)) {
System.out.println("Computer Choose"+result
);
Cwin++;
}else {
System.out.println("Computer Choose"+result);
tie++;
}
} else if(YoN.equalsIgnoreCase("no")) {
System.out.println("Computer wins: " + Cwin + "\nUser wins: " + Uwin+"\nTie: "+tie);
System.out.println("Thank you");
break;
}else {
System.out.println("Enter valid input");
}
}
}
}
Track the score separately from the individual game
It looks you've written your game() method to play a single game of Rock, Paper, Scissors. In that case, you only need to return one value: who won that single game. Then your main method can keep track of the current scores and print out the totals after it's all done.
Consider an approach like the following:
import java.util.*;
public class rockPaperScissors {
public final static int USER_WON = 1; // Added these constants
public final static int COMPUTER_WON = 2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Uwin = 0;// user win count // Moved from `game()`
int Cwin = 0;// computer win count // Moved from `game()`
System.out.println("Play again? Type yes or no.");
String YoN = input.next();
if (YoN.equalsIgnoreCase("yes")) {
int winner = game(); // Modified this line
if (winner == USER_WON) { // Added this section
Uwin++;
} else {
Cwin++;
}
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static int game() { // Modified this line
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
//// Truncating for brevity ////
if (choice == 3 && result == 1) {
return COMPUTER_WON; // Modified this line
}
if (choice == 2 && result == 1) {
return USER_WON; // Modified this line
}
//// Truncating for brevity ////
}
}
Notice that I moved the Uwin and Cwin variables out of game() and into your main method. Then I changed game() to return an integer instead of nothing (void) and replaced the Cwin++ and Uwin++ statements with a simple return COMPUTER_WON or return USER_WON based on the results of the rock, paper, scissors match. That return value can then be processed in your main method to keep a running total of how many games each player has won.
Use a class
If you're interested in trying something more advanced, consider creating an Object to encapsulate the two values you want to return.
For example, by storing both win counts in a simple Scoreboard object like the one below would enable you to return the two win counts at the same time and encapsulate the process of printing the scoreboard to the screen.
If you go this route, you'd have to make sure that all games reference the same Scoreboard. There are a variety of ways to do this from using a class variable, to passing the Scoreboard as a function parameter to the game() method, to moving all your logic for playing multiple games into the game() method. There are lots of options for you to try out and see which works best for you in this situation.
public class Scoreboard {
private int computerWins;
private int playerWins;
public Scoreboard() {
computerWins = 0;
playerWins = 0;
}
public void addComputerWin() {
computerWins++;
}
public void addPlayerWin() {
playerWins++;
}
#Override
public String toString() {
return "Scoreboard: "
+ "\n - Computer wins: " + computerWins
+ "\n - Player wins: " + playerWins;
}
}
I coded a fishing game simulator. I want to control the answer: If answer is not equal to "Y","y","N" or "n", Ask again : Would Like to fish? until until the user presses the correct key. I do not know how to code this algorithm and which line should I put that algorithm. My code is here:
// --------------------//
import java.util.Random;
import java.util.Scanner;
public class fishinggame {
public static void main(String[] args) {
Random dice = new Random();
Scanner scanner = new Scanner(System.in);
int randomGuess;
String choice = "Y";
int score = 0;
int points = 0;
int counter = 0;
System.out.println("Let's go fishing!!!");
System.out.println();
System.out.println("Would you like to fish?");
System.out.println("Type Y or y for yes");
System.out.println(" Type N or n for quit");
while (choice.equalsIgnoreCase("Y")) {
randomGuess = dice.nextInt(6) + 1;
if (randomGuess == 1) {
System.out.println("You caught an old shoe.");
points += 1; // If Random Guess is 1 player takes that message and wins 1 point
}
if (randomGuess == 2) {
System.out.println("You caught a huge fish!");
points += 100; // If Random Guess is 2,player takes that message and wins 100 points
}
if (randomGuess == 3) {
System.out.println("You caught a leaf ");
points += 2; // If Random Guess is 3,player takes that message and wins 2 points
}
if (randomGuess == 4) {
System.out.println("You caught a small fish ");
points += 50; // If Random Guess is 2,player takes that massage and wins 50 points
}
if (randomGuess == 5) {
System.out.println("You caught a rock ");
points += 3; // If Random Guess is 2,player takes that massage and wins 3 points
}
if (randomGuess == 6) {
System.out.println("You caught a garbage ");
points += 0; // If Random Guess is 2,player takes that massage and can not win any point
}
System.out.println("Want to try again? Y/N");
choice = scanner.nextLine();
counter++; // This structure counts repeat of game
}
if ((choice.equalsIgnoreCase("N"))) {
System.out.println("Game Over");
System.out.println();
System.out.println("Your final score is: " + (points));
System.out.println("Your game repeat is:" + counter);
double avarege = (double) points / counter; // This lane is for counting the average of points
System.out.printf("Your Average Point Is: %6.2f\n" , avarege);
if (avarege >= 20) {
System.out.println("GREAT JOB");
} else if (avarege >= 10) {
System.out.println("That is some fine fishing");
} else {
System.out.println("Try again in future!");
}
System.out.println("Thanks for playing!");
}
}
}
Solution :
import java.util.Random;
import java.util.Scanner;
public class fishinggame {
public static void main(String[] args) {
Random dice = new Random();
Scanner scanner = new Scanner(System.in);
int randomGuess;
String choice = "Y";
int score = 0;
int points = 0;
int counter = 0;
System.out.println("Let's go fishing!!!");
System.out.println();
System.out.println("Would you like to fish?");
System.out.println("Type Y or y for yes");
System.out.println(" Type N or n for quit");
choice = scanner.next();
while (!choice.equalsIgnoreCase("Y") && !choice.equalsIgnoreCase("n")) {
System.out.println("Would you like to fish?");
System.out.println("Type Y or y for yes");
System.out.println(" Type N or n for quit");
choice = scanner.next();
}
while (choice.equalsIgnoreCase("Y")) {
randomGuess = dice.nextInt(6) + 1;
if (randomGuess == 1) {
System.out.println("You caught an old shoe.");
points += 1; // If Random Guess is 1 player takes that message and wins 1 point
}
if (randomGuess == 2) {
System.out.println("You caught a huge fish!");
points += 100; // If Random Guess is 2,player takes that message and wins 100 points
}
if (randomGuess == 3) {
System.out.println("You caught a leaf ");
points += 2; // If Random Guess is 3,player takes that message and wins 2 points
}
if (randomGuess == 4) {
System.out.println("You caught a small fish ");
points += 50; // If Random Guess is 2,player takes that massage and wins 50 points
}
if (randomGuess == 5) {
System.out.println("You caught a rock ");
points += 3; // If Random Guess is 2,player takes that massage and wins 3 points
}
if (randomGuess == 6) {
System.out.println("You caught a garbage ");
points += 0; // If Random Guess is 2,player takes that massage and can not win any point
}
System.out.println("Want to try again? Y/N");
choice = scanner.next();
counter++; // This structure counts repeat of game
}
if ((choice.equalsIgnoreCase("N"))) {
System.out.println("Game Over");
System.out.println();
System.out.println("Your final score is: " + (points));
System.out.println("Your game repeat is:" + counter);
double avarege = (double) points / counter; // This lane is for counting the average of points
System.out.printf("Your Average Point Is: %6.2f\n" , avarege);
if (avarege >= 20) {
System.out.println("GREAT JOB");
} else if (avarege >= 10) {
System.out.println("That is some fine fishing");
} else {
System.out.println("Try again in future!");
}
System.out.println("Thanks for playing!");
}
}
}
The result :
Let's go fishing!!!
Would you like to fish?
Type Y or y for yes
Type N or n for quit
y
You caught a leaf
Want to try again? Y/N
y
You caught a rock
Want to try again? Y/N
y
You caught a small fish
Want to try again? Y/N
y
You caught a small fish
Want to try again? Y/N
n
Game Over
Your final score is: 105
Your game repeat is:4
Your Average Point Is: 26,25
GREAT JOB
Thanks for playing!
Assignment Instructions:
-Prompt the user in main() if he she want to play the game or not. Display a brief description of how the game should be played first.
-Code a method that allows the user to play
-Code a method for the computer throwing two dices.
-Code a method that displays the outcome by showing what the user entered, the user to play as many times as he.she wish...and each time, you must keep track of the number of wins and losses by the player.
-Code a method that display the statistics for all games played and as soon as the player chooses to abort the game. You must display the number of games played, how may were won, how many were lost, and the percentile for each
My problem is keeping track of the number of wins and losses by the player and displaying the correct amount of games that was played, won and loss after multiple turns at the game. (Specifically in the stats() method) I tried to add to the userwins and userloss with "++" but it doesn't remember the amount of games played when the user plays 1 to play another game. If the ++ doesn't work, I believe I should do a counter for it. However, I don't know if this counter should go in main or within the Stats() method.
public class DiceGame_
{
//declarations:
static int answer = 1;//1 to continue or 0 to quit
static Scanner get = new Scanner(System.in);
static int guess = 0;
static int dice1 = 0;
static int dice2 = 0;
static int dicesum = 0;
static int games = 0;
static int userWins = 0;
static int userLoss = 0;
static double percentW = 0;
static double percentL = 0;
static Random random = new Random();
public static void main(String[] args)
{
//Display the game's description and Prompt the user if they would like to play
System.out.println("In this game, you are playing against the computer. The computer will throw 2 dices"
+ " to randomly select 2 numbers between 1 and 6.\nYou will then guess a number between 2 and 12, if the number"
+ " you guess matches the sum of the two dices the computer throws,\nthen you win! Otherwise, the computer wins.");
//input:
while (answer != 0) //while will allow the user to play again
{
GuessNum(); //call GuessNum method
DiceThrow();//call DiceThrow method
//Output:
DispOutcome();//Display outcome method
//ask user if they would like to continue
System.out.println("Would you like to play again? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}//end while
Stats();//Stats Method (Display # of games played, won and loss, and percentiles of wins/losses)
}//end main
//==========================================================
public static void GuessNum() //The user guesses a number Method
{
System.out.println("Please enter a number between 2-12 for your guess.");
guess = get.nextInt();
while(guess < 2 || guess > 12) //will make sure the user is asked again if they enter a value greater than 12 or less than 2
{
System.out.println("You must select a number between 2 and 12! Please re-enter a guess: ");
guess = get.nextInt();
}//end while
}//end GuessNum method
//==========================================================
public static void DiceThrow() //The computer generates 2 numbers from dice rolls
{
dice1 = random.nextInt(6) + 1;
dice2 = random.nextInt(6) + 1;
dicesum = dice1 + dice2;
}//end DiceThrow method
//==========================================================
public static void DispOutcome() //Displays the outcome of what the user entered, the values of the 2 dice thrown and who won
{
System.out.println("Computer: Dice 1 = " + dice1 + " and Dice 2 = " + dice2);
System.out.println("Player: entered " + guess);
System.out.println("You played " + guess + " and the compuer threw " + dice1 + " and " + dice2 +
" for a total of " + dicesum + "....");
{
if(guess == dicesum)
System.out.println("You won!");
else if(guess != dicesum)
System.out.println("Sorry! You lost!");
}//end if
}//end DispOutcome method
//==========================================================
public static void Stats() //Displays the stats of the game (wins, losses, percentile of each)
{
{
if(guess == dicesum)
userWins ++; //adds 1 to the user's win count if the user wins a game
else if (guess != dicesum)
userLoss ++; //adds 1 to the user's loss count if the user losses the game
}
games = (userWins + userLoss); //total of games is the losses + wins
System.out.println("You've played: " + games + " games");
System.out.println("You've won: " + userWins + " games");
System.out.println("You've loss: " + userLoss + " games");
percentW = (userWins / games);
percentL = (userLoss / games);
System.out.println ( String.format("Your win percentage is %.2f", + (percentW * 100)) + "%");
System.out.println ( String.format("Your loss percentage is %.2f", + (percentL * 100)) + "%");
}//end Stats method
}//end class DiceGame_
You are only calling the Stats() method once, when done, so the userWins++ and userLoss++ statements are only called once. You should move those statements inside the DispOutcome() method so they get called for every game. You already have a check for (guess == dicesum) there, which is where they go.
I can see 2 problems:
Problem #1.
percentW = (userWins / games);
percentL = (userLoss / games);
The variables userWins, games and userLoss are all integers. So the divisions are going to be treated as integer arithmetic. That is going to cause percentW and percentL to be 0.0.
Hint: to force the division to be done using floating point, convert either or both operands to be double. Have you been taught how to convert from one primitive type to another?
Problem #2.
The incrementing of the variables happens in the Stats method. The Stats method is called only once. Therefore the variables only get incremented once.
Hint: if the purpose of Stats is to print out the stats, then you are incrementing the score in the wrong method.
By the way, there are a few problems with style and other things:
Method names should not start with an uppercase letter in Java.
The indentation is inconsistent. I suspect that you are using TAB characters in the source file. This causes problems if you cut-and-paste code into Markdown ... and in other contexts. For example Linux/Mac versus Windows!
It is better to configure your IDE to use SP characters for indentation.
There are issues with how you are using { ... }. For example:
{
if (guess == dicesum)
System.out.println("You won!");
else if (guess != dicesum)
System.out.println("Sorry! You lost!");
}
If you look at that, the braces serve no real purpose there.
In a statement like this:
GuessNum(); //call GuessNum method
the comment is (IMO) harmful. It says nothing that isn't totally obvious from the code. In fact, all it really does is distract the reader.
This code should be OO. You are relying heavily on static methods and static variables. (Maybe that is the next lesson ....)
i'm new to java. i'm writing a sample of rock paper scissors game. the user input 0,1,2 for rock, paper, scissors respectively. the program randomly generated the result. i almost managed to get it work but the only thing i'm stuck at is how to STOP THE FOR LOOP IF ONE OF THE SIDE WINS CONSECUTIVELY FOR THREE TIMES.
THIS IS THE ORIGINAL QUESTION
Write a program that plays scissor-rock-paper game. The rule is that a scissor wins against a paper, a
rock wins against a scissor, and a paper wins against a rock. The program represent scissor as 0, rock
as 1, and paper as 2.
The game is to be played between the computer and a player. The program will prompt the user to
enter the number of rounds to win. For example, if the user enter 4 then the winner has to win at
least 3 out of the 4 rounds. If either party win 3 times consecutively, the game ends early without the
fourth round. If the user enter 5 rounds, the winner has to win at least 3 out of the 5 rounds. The
same rule of consecutive 3-wins also apply. After the user has entered the number of rounds, the
computer randomly generates a number between 0 and 2. The program then prompts the user to
enter a number 0, 1, or 2. After the last round (subject to the above mentioned early-winner-rule),
the program display a message indicating whether the computer or the user wins, loses, or draws.
THIS IS MY CODE.
package assignment1;
import java.util.Scanner;
import java.util.Random;
public class question1_9 {
// This program is used to play scissor-rock-paper game.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random random = new Random();
int scissor = 0, rock = 1, paper = 2, round, userinput,comprand, userresult = 0, compresult = 0, control,j,k;
// Variables used in this program is declared and initialized.
/* Number of rounds wished to be play are obtained from user. */
System.out.println("WELCOME TO ROCK PAPER SCISSOR GAME. ");
System.out.println("PLEASE ENTER THE NUMBER OF ROUND YOU WANT TO PLAY: ");
round = scan.nextInt();
control = (round/2)+1;
for(int i = 0; i<round; i++)
{
if (compresult == control | userresult == control)
{
break;
}
System.out.println("ROUND " + (i+1));
System.out.println("PLEASE ENTER:\n 0 for scissor \n 1 for rock \n 2 for paper \n");
userinput = scan.nextInt();
comprand = random.nextInt(3);
if (userinput == 0)
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("DRAW!!!");
i--;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("YOU WIN!!!");
userresult++;
}
}
else if (userinput == 1)
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("YOU WIN!!!");
userresult++;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("DRAW!!!");
i--;
}
}
else
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("YOU WIN!!!");
userresult++;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("DRAW!!!");
i--;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
}
}
if(compresult == userresult)
System.out.println("\n\nFINAL RESULT IS DRAW!!!");
else if (compresult > userresult)
System.out.println("\n\nFINAL RESULT IS COMPUTER WIN!!!");
else
System.out.println("\n\nFINAL RESULT IS YOU WIN!!!");
}
}
use break; statement when you want to get out of current loop.
At top of loop,
store the wins in an array
String[] results=new String[rounds];
store your results as "user" or "comp" for each round and at the end of loop do this
if((results[i].equals("user") && results[i-1].equals("user") && results[i-2].equals("user") || (results[i].equals("comp") && results[i-1].equals("comp") && results[i-2].equals("comp")))
{
break;
}
Like shreyas said, use a break statement when you want to exit a loop.
I would set compresult to zero whenever the player wins a round, and set userresult to zero whenever the computer wins. Then, at the top of the loop, right after the { add:
if(userResult == 3 || computerResult == 3 || round/2 > 10)
{
break;
}
Some code comes from shreyas's original post.
I have been working on this program for about a week now and I think I have it down pack. The issue I am having when I ask the user at the beginning of the game (human vs computer) every time I run the program it asks me what my name is again. Here is what I have thus far:
import java.util.Scanner;
public class Assignment
{
Scanner usersName;
Boolean humanTurn = true;
Boolean computerTurn = true;
int dice;
int humanTurnPoints, computerTurnPoints;
int humanTotalPoints = 0;
int computerTotalPoints = 0;
private Scanner keyboard;
private Scanner key;
//System.out.print("Please enter your name: ");
//usersName = new Scanner(System.in);
//setStart(usersName.nextLine());
public void roll()
{
dice = (int)(Math.random()*6) + 1;
}
public int humanTurnScore()
{
{
humanTurnPoints = dice + humanTurnPoints;
System.out.println("You threw: " + dice);
System.out.println("You have scored: " + humanTurnPoints + " in your turn.");
} return humanTurnPoints;
}
public void humanTurnZero()
{
humanTurnPoints = 0;
}
public int computerTurnScore()
{
{
computerTurnPoints = dice + computerTurnPoints;
System.out.println("Computer has scored: " + computerTurnPoints + " in its turn.");
} return computerTurnPoints;
}
public void computerTurnZero()
{
computerTurnPoints = 0;
}
public Assignment()
{
humanGame();
if(!humanTurn)
{
computerTurn();
}
}
public int humanGame()
{
System.out.println("To start the game please press 'r'.");
key = new Scanner(System.in);
String start = key.nextLine();
if(!start.equalsIgnoreCase("R"))
{
System.out.println("Make sure you are pressing 'r'.");
humanGame();
}
if(start.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets start.");
do{
roll();
if(dice == 1)
{
System.out.println("You got 1 and you lost your turn.");
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
humanTurnZero();
computerTurn();
}
else if(dice != 1)
{
humanTotalPoints += dice;
if(humanTotalPoints >= 100)
{
System.out.println("You threw: " + dice);
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Congratulations, you win!");
System.exit(0);
}
humanTurnScore();
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("You can hold or roll again.");
System.out.println("To roll again press 'r' or 'h' to hold.");
keyboard = new Scanner(System.in);
String choice = keyboard.nextLine();
if(choice.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets roll again.");
roll();
if(!choice.equalsIgnoreCase("R"))
{
System.out.println("You didn't press 'r'. To make sure the program is running correctly please press 'r' to roll or 'h' to hold.");
humanGame();
}
}
if(choice.equalsIgnoreCase("h"))
{
System.out.println("You pressed 'h' and loose your turn.");
System.out.println("Your Grand total is: " + humanTotalPoints);
humanTurnZero();
computerTurn();
}
}
}while(humanTurn);
}return dice;
}
public int computerTurn()
{
System.out.println("Now it's computer turn.");
do {
roll();
if(dice != 1)
{
computerTotalPoints += dice;
if(computerTotalPoints >=100)
{
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Game Over! the computer wins");
System.exit(0);
}
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Your Grand total is: " + humanTotalPoints);
computerTurnScore();
roll();
}
if(dice == 1)
{
System.out.println("Computer thrown 1 therefore it's your turn now.");
computerTurnZero();
humanGame();
}
if(computerTurnPoints >= 20)
{
System.out.println("Computer scored already " + computerTurnPoints + " you'd better start to focus.");
System.out.println("Please play again");
humanGame();
}
}while (computerTurn);
return dice;
}
public static void main(String[] args)
{
new Assignment();
}
}
I commented out (up close to the top of the program) where I am asking the user at the beginning of the program what their name is. I actually need in all the System.out.println where it says 'You' I need it to say the usersName.
Would someone please help me with this program. I know someone is kind enough to help me out here.
Thank you in advance.
Of course it will ask you that every time!
You need to save this in a file, and then read from it!
//Write
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println(usersName.nextLine());
writer.close();
//Read
BufferedReader br = new BufferedReader(new FileReader("the-file-name.txt"));
try {
while (line != null) {
usersName = line;
line = br.readLine();
}
} finally {
br.close();
}
Add your logic for determining if there is sth in that file yourself please.
Okay, I think you might be getting confused about the lifetimes of variables. In java, variables like String username; exist only in their own scope.
If you define a variable inside a method, it will be forgotten about when the program exists the method.
If you define it as a field inside a class (what you were doing), it will only exist as long as the instance of the class exists. As soon as the program forgets about the instance of the class, it also forgets about anything attached to that instance, including its variables.
Once the program shuts down, the computer naturally forgets about all objects that the program held, and so the username ceases to exist.
If you want the program to remember some value across shutdowns, you have to store that value in a file or a database or whatever. I recommend using a file, to make a database for this would be overkill squared. I will refer you to Roberto's answer from an hour ago for more info on how to achieve this exacly.