Java replay when certain character typed - java

When number 0 is typed after the guess is correct, it should replay the game. It just returns the message "0 to play again and 1 to quit"
public static void main(String[] args) {
boolean game = true; //true means the game will continue playing, false stops the game
Scanner input = new Scanner(System.in);
System.out.println("Guess: ");
while (game) {
HiLo mainGame = new HiLo();
mainGame.generateRandomNumber();
boolean guessCorrect = false;
while (!guessCorrect) {
int inputted = input.nextInt();
if (inputted == 101) {
guessCorrect = true;
System.out.println("quitted");
}
System.out.println(mainGame.checkGuess(inputted));
mainGame.getGuessCounter();
if (mainGame.checkGuess(inputted) == "Correct! You got it right!") {
guessCorrect = true;
System.out.println("Correct after " + mainGame.getGuessCounter() + " guesses");
}
}
while (guessCorrect = true) {
System.out.println("Would you like to play again? (0 : YES) (1 : NO)");
System.out.println("Your answer: ");
int answer = input.nextInt();
//issues with inputting 0 and restarting game
if (answer == 0) {
game = true;
}
else if (answer == 1) {
guessCorrect = true;
System.out.println("Game Over");
}
else {
System.out.println("Error, can't understand the meaning");
guessCorrect = false;
}
}
}
}

Change while (guessCorrect = true) to while (guessCorrect). Set guessCorrect to false to exit the while (guessCorrect) loop and proceed to restarting or exiting the game. Make sure to set the game to false if answer is not equal to 0 to exit the game.
while (guessCorrect) {
System.out.println("Would you like to play again? (0 : YES) (1 : NO)");
System.out.println("Your answer: ");
int answer = input.nextInt();
//issues with inputting 0 and restarting game
if (answer == 0) {
game = true;
}
else if (answer == 1) {
System.out.println("Game Over");
game = false;
}
else {
System.out.println("Error, can't understand the meaning");
game = false;
}
guessCorrect = false;
}

Related

How can I start the program over again

I'm trying to start the game over if the user enters "Yes". I tried using a while loop, but it's gone wrong somewhere that I can't find.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
int playerScore = 0;
int computerScore = 0;
int round = 0;
String decision;
// Get user input
while (round<3) {
System.out.println("Please enter your move: Rock, Paper or Scissors");
System.out.println(">>");
Scanner input = new Scanner(System.in);
String playerMove = input.next();
// Check if user input is valid
if (!playerMove.equalsIgnoreCase("Rock") && !playerMove.equalsIgnoreCase("Paper") && !playerMove.equalsIgnoreCase("Scissors")) {
System.out.println("Move is invalid, Opponent gets a point");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else {
// Randomly generate computerMove
int computerInt = (int)(Math.random()*3);
String computerMove = " ";
if (computerInt == 0) {
computerMove = "Rock";
} else if (computerInt == 1) {
computerMove = "Paper";
} else if (computerInt == 2) {
computerMove = "Scissors";}
System.out.println("Opponent move is "+ computerMove);
// Establish winning or losing scenarios
if (playerMove.equalsIgnoreCase(computerMove)) {
System.out.println("Tied");
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else if (playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Scissors") ||
playerMove.equalsIgnoreCase("Scissors") && computerMove.equalsIgnoreCase("Paper") ||
playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Paper")) {
System.out.println("You won");
playerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
else {
System.out.println("You lost");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
}
// Determine the last winner
if (playerScore < computerScore) {
System.out.println("You lose, so sad ;(");
} else if (playerScore > computerScore) {
System.out.println("You win, here's a cookie ;) ");
} else {
System.out.println("Tied, maybe try harder ^_^"); }
}
System.out.println("Do you wanna play again?");
}
}
}
Sounds like this might be a HW or Test question, so just writing steps to help you out:
first have a user-decision variable and initialize it to "Y"
then put the game in a while(user-decision="Y") loop
at the end of this loop ask the user for their decision and update the user-decision variable to either Y or N
if they say Y loop continues, else it ends
if you need to repeat your code, put it in a new class (Game) and instantiate in main () and call until your Game class returns TRUE (press Y)
package appMain;
import java.util.Scanner;
public class Game {
public Boolean PlayGame() {
System.out.println("START GAME");
//
// >> PUT THERE YOUT GAME CODE <<
//
Scanner input = new Scanner(System.in);
String answer = input.next();
if(answer.equals("Y")) {
return true;
}
return false;
}
}
package appMain;
public class GameMain {
public static void main(String args[]) {
Game game = new Game();
while (game.PlayGame()) {
}
System.out.println("GAME finish");
}
}

Best way to code my unintelligent Nim game?

This is my nim game (goal is dont be the last person to pick up marbles), can someone please guide me. In playing the game, I have just one question
How can I keep track of whose turn it is, I guess if I can keep track of that I can monitor my remainingMarbles. This is the crux of my code. Please help
public class Nim{
public static void main(String[] args)
{
System.out.println("************** Welcome to the game of Nim *******************");
System.out.println("The object of this game is to make me take the last marble off the table");
System.out.println("You must take at least 1 and you can take up to 3 marbles on your turn");
System.out.println("You can go first");
Scanner scan = new Scanner(System.in);
final int MARBLES = 13;
int remainingMarbles;
String input;
do {
//boolean whoseTurn = true;
remainingMarbles = MARBLES;
System.out.println("There are " + MARBLES + " marbles on the table");
while (remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
}
if (1 <= remainingMarbles && remainingMarbles <= 2 && remainingMarbles < 0) {
System.out.println("Congratulations! you won!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
} else
System.out.println("Hard luck you lose!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
}while (input.charAt(0) == 'y');
}
private static int getUserSelection()
{
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter 1, 2 or 3");
int userSelection = scan.nextInt();
if (isValidMove(userSelection)){
return userSelection;
}
else {
System.out.println("Not a valid entry");
}
}while (true);
}
private static boolean isValidMove(int input)
{
return 1 <= input && input <= 3;
}
private static int getComputerSelection ()
{
Random generator = new Random();
int computerSelection = 1 + generator.nextInt(3);
System.out.println("The computer chooses " + computerSelection);
return computerSelection;
}
}
First, make a boolean before the loop.
boolean whoseTurn = true;
When the variable is true it's the first player's turn, otherwise the second player's turn.
Now inside the while loop we change the variable at the end of every repetition:
whoseTurn = !whoseTurn;
(Which is a faster way of this)
if(whoseTurn) whoseTurn = false;
else whoseTurn = true;
To conclude, you should do something like that:
...
boolean whoseTurn = true;
while(remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
whoseTurn = !whoseTurn;
}
...

How to generate a random number after user guess the correct number?

I have written the code below. I have run the program and it allows the user to guess the correct number and return the message successfully. However, I couldn't get it to regenerate a new random number? I also couldn't include an option to ask whether the user wants to quit or not. Please help. Thank you.
import java.util.*;
class CompterAge {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
boolean correctGuess = false;
Random r = new Random();
int randNum = r.nextInt(100-1+1) + 1;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input == "Yes") {
correctGuess = false;
} else {
break;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
}
This code works, I have added another flag variable and corrected some logical errors. See the comments.
boolean correctGuess = false;
boolean endGame = false;
Random r = new Random();
while (!endGame){
int randNum = r.nextInt(101); //Why did you have (100-1+1) + 1 ?? Simple (101) was enough
correctGuess = false;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
correctGuess = true; //Will exit the Inner Loop
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next().toLowerCase();
if (input.equals("yes")) { //You can not use == for String Comparisons
endGame = false;
} else {
endGame = true;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
Your random number generation is done outside of your while loop so when they input that they want to continue the game it should then generate a new number:
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input.equals("Yes")) {
randNum = r.nextInt(100-1+1) + 1;
correctGuess = false;
} else {
break;
}

Rock, Paper, Scissors- BlueJ crazy loop

the following is my code for a rock, paper, scissors game in BlueJ. When I compile and the user enters an input, the computer immediately prints numerous outputs from playerWins(). The game ends when the user types "quit". Could someone help me so my screen won't be flooded? (and if there is any way to condense my code that would also be great).
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors
{
public static void main(String[] args)
{
int wins = 0, losses = 0, ties = 0;
boolean output;
Scanner scan = new Scanner(System.in);
System.out.print("(R)ock, (P)aper, (S)cissors, or quit: ");
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false)
{
playerChoice = playerChoice.toUpperCase();
String computerChoice = getComputerChoice();
if(playerChoice.equals(computerChoice) != true)
{
output = playerWins(playerChoice, computerChoice);
if (output == true)
{
wins++;
}
else if (output == false)
{
losses++;
}
}
else
{
ties++;
System.out.println("Tie!");
}
}
System.out.println("QUIT");
System.out.println("Wins: " + wins);
System.out.println("Losses: " + losses);
System.out.println("Ties: " + ties);
scan.close();
}
public static String getComputerChoice()
{
Random gen = new Random();
int num = gen.nextInt(30) + 1;
if (num % 3 == 2)
{
return "R";
}
else if (num % 3 == 1)
{
return "P";
}
else
{
return "S";
}
}
public static boolean playerWins(String playerChoice, String computerChoice)
{
if (playerChoice.equals("R") == true)
{
if (computerChoice.equals("P") == true)
{
System.out.println("My Point! \nP beats R"); // Rock is beaten by paper
return false;
}
else if (computerChoice.equals("S") == true)
{
System.out.println("Your Point! \nR beats S"); // Rock beats scissors
return true;
}
}
else if (playerChoice.equals("P") == true)
{
if (computerChoice.equals("R") == true)
{
System.out.println("Your Point! \nP beats R"); //Paper beats rock
return true;
}
else if (computerChoice.equals("S") == true)
{
System.out.println("My Point! \nS beats P"); //Paper is beaten by scissors
return false;
}
}
else if (playerChoice.equals("S") == true)
{
if (computerChoice.equals("P") == true)
{
System.out.println("Your Point! \nS beats P"); //Scissor beats paper
return true;
}
else if (computerChoice.equals("R") == true)
{
System.out.println("My Point! \nR beats S"); //Scissors is beaten by rock
return false;
}
}
return false;
}
}
These two lines are the problem:
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false) {
You are reading one line and then checking that line over and over again. You need to read a new line inside the loop. The way you have it now, it is just trying to make the same move over and over infinite times.
Try:
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false) {
//do all of the stuff that is already inside your loop
playerChoice = scan.nextLine();
}
This will get user input again every time after processing the last input.
You are checking the user-input only once, that is before the loop:
String playerChoice = scan.nextLine();
One very nice method to solve that is the following:
String playerChoice;
while((playerChoice = scan.nextLine()).equals("quit") == false)
{
//more code
}
What the above code does, is that playerChoice is set right before .equals("quit") is called. If you use this method you don't need one more line at the end of your loop to set playerChoice but just do that in the head of your loop.

Heads or Tails Game - Loop Issues

import java.util.Scanner;
import javax.swing.JOptionPane;
public class Coin {
public static void main(String[] args)
{
boolean validFinalInput = false;
boolean validBetInput = false;
boolean validGuessInput = false; //Determines if the guess is a valid input
boolean validBet = false; //Determines if the bet is valid
boolean goAgain = true;
double num; //Unparsed Side Determiner
double balance = 100;
String Bet = null; //Bet Input
double bet = 0; //Parsed Bet
String Guess = null; //H or T
String Side = null; //Determines Side
String GoAgain = null; //Y/N Retry input
Scanner in = new Scanner(System.in);
while (goAgain == true){ //While true, the player will keep playing.
num = Math.round(Math.random()); //Declares Number
if (num == 1){
Side = "H";
} else if (num == 0){
Side = "T";
}
while (validGuessInput == false){ //Determines if the input is valid
System.out.println("Guess: (H/T)");
Guess = in.next();
if (Guess.equals("H") || Guess.equals("T")){
validGuessInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Guess!");
validGuessInput = false;
}
}
while (validBet == false){
while (validBetInput == false){
try {
System.out.println("Bet? (Your balance is $" + balance);
Bet = in.next();
bet = Double.parseDouble(Bet);
if (bet > 0){
validBetInput = true;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid Bet!");
}
}
if (bet <= balance && bet >= 0){
validBet = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Bet!");
validBet = false;
}
}
if (Guess.equals(Side)){
balance = balance + (bet * 2);
System.out.println("Correct! The side was: " + Side);
System.out.println("Your balance is now: $" + balance);
} else {
balance = balance - bet;
System.out.println("Incorrect! The side was: " + Side);
System.out.println("Your balance is now: $" + balance);
}
if (balance == 0){
System.out.println("You ran out of money. Ending Game.");
break;
}
System.out.println("Go again? (Y/N)");
GoAgain = in.next();
while (validFinalInput == false);
System.out.println("Go again? (Y/N)");
GoAgain = in.next();
validGuessInput = false;
validBet = false;
validBetInput = false;
if (GoAgain.equals("Y")){
goAgain = true;
validFinalInput = true;
} else if (GoAgain.equals("N")){
goAgain = false;
validFinalInput = true;
System.out.println("Thanks for playing! You ended with: $" + balance);
} else {
System.out.println("Invalid Input!");
}
}
}
}
So I wrote this code for a "Heads or Tails" style game. It originally worked, but then I decided to add a few features, and it busted. Basically, it gets to the end, but is stuck on the last input (Y/N).
Could someone show me what I'm doing wrong?
Sorry for the lack of commenting.
I also am aware my variables don't quite follow conventions, so sorry for that too.
Thanks.
Remove the semicolon here;
while (validFinalInput == false);
Indent your code properly.
Check your logic here; You are setting validFinalInput = true for both the conditions (true and false).
if (GoAgain.equals("Y")){
.........
validFinalInput = true; }
else if (GoAgain.equals("N")){
.......
validFinalInput = true; }
The value of goAgain never changes in the loop that starts with while (goAgain == true){ because it ends with the } just before while (validBet == false){. That closing bracket is misplaced.
You have this while statement
while (validFinalInput == false);
This is an infinite loop! it will never get past this part of the code because of the semicolon. If you rewrite it like this it should work:
while (validFinalInput == false)
{
System.out.println("Go again? (Y/N)");
GoAgain = in.next();
validGuessInput = false;
validBet = false;
validBetInput = false;
if (GoAgain.equals("Y"))
{
goAgain = true;
validFinalInput = true;
}
else if (GoAgain.equals("N"))
{
goAgain = false;
validFinalInput = true;
System.out.println("Thanks for playing! You ended with: $" + balance);
}
else
{
System.out.println("Invalid Input!");
}
}

Categories

Resources