Alright, I have a class assignment to create 3 predetermined methods for a rock, paper, scissors program written by the teacher. However, when I run the program it running the methods multiple times in a row. I've looked through the code several times and can't figure out the problem.
Below is the teacher provided portion of the program:
public class Game
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
RockPaperScissors rps = new RockPaperScissors (); //***Your class
int numGames = 0;
String userChoice = "";
String cpuChoice = "";
String winner = "";
int userWins = 0;
int cpuWins = 0;
System.out.println("Welcome to Rock, Paper, Scissors!\n");
//Get odd number of games
System.out.println("How many rounds would you like to play?");
numGames = in.nextInt();
while (numGames % 2 == 0) //Even number
{
System.out.println("Sorry, number of games must be odd. Please try again:");
numGames = in.nextInt();
}
//Flush the buffer
in.nextLine();
//Play the game for the number of rounds the user entered
for (int i = 1; i <= numGames; i++)
{
//Get the user and computer choices
userChoice = rps.getUserChoice(); //***Your method
cpuChoice = rps.getCPUChoice(); //***Your method
System.out.println("Computer chooses " + cpuChoice);
//Pick winner
winner = rps.pickWinner(userChoice, cpuChoice); //***Your method
if (winner.equalsIgnoreCase("Tie"))
{
System.out.println("It's a tie! Play again.");
numGames++;
}
else
{
if (winner.equalsIgnoreCase("User"))
{
userWins++;
}
else if (winner.equalsIgnoreCase("Computer"))
{
cpuWins++;
}
else
{
System.out.println("Error in picking winner");
}
System.out.println(winner + " wins!");
}
} //end for
//Print results
System.out.println("\nUser wins: " + userWins);
System.out.println("Computer wins: " + cpuWins);
if (userWins > cpuWins)
{
System.out.println("\nThe user won!");
}
if (cpuWins > userWins)
{
System.out.println("The computer won!");
}
//Close game
System.out.println("\nThank you for playing!");
} //end main
} //end class
And here is my code which I'm assuming where the problem is coming from:
public class RockPaperScissors {
public String getUserChoice() {
Scanner sc = new Scanner (System.in);
System.out.println("Enter your choice:");
String userInput = sc.nextLine();
boolean end = true;
while (end == true){
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
end = false;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
userInput = sc.next();
}
}
return userInput;
}// end getUsechoice
public String getCPUChoice() {
String computerChoice = " ";
Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
if (randomNum == 1){
computerChoice = "rock";
}
else if (randomNum == 2){
computerChoice = "paper";
}
else if (randomNum == 3){
computerChoice = "scissors";
}
return computerChoice;
}
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (getUserChoice().equalsIgnoreCase("rock")) {
if (getCPUChoice().equalsIgnoreCase("rock")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("paper")){
result = "Computer";
}
else if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (getUserChoice().equalsIgnoreCase("paper")){
if (getCPUChoice().equalsIgnoreCase("paper")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("rock")){
result = "User";
}
else if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (getUserChoice().equalsIgnoreCase("Scissors")){
if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("rock")){
result = "Computer";
}
else if (getCPUChoice().equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
}//end pickWinner
}//end rockPaperScissors
Here would be a sample session of the program:
Welcome to Rock, Paper, Scissors!
How many rounds would you like to play? 1 Enter your choice: rock
Computer chooses paper Enter your choice: rock Enter your choice: rock
Computer wins!
User wins: 0 Computer wins: 1 The computer won!
Thank you for playing!
Here I'm wondering why it continues asking for user input multiple times. Also it runs the other methods as well which is why the computer won despite picking paper vs rock.
Alright added in the final changes to my program and it's working perfectly now:
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (userChoice.equalsIgnoreCase("rock")) {
if (cpuChoice.equalsIgnoreCase("rock")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("paper")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (userChoice.equalsIgnoreCase("paper")){
if (cpuChoice.equalsIgnoreCase("paper")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "User";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (userChoice.equalsIgnoreCase("Scissors")){
if (cpuChoice.equalsIgnoreCase("scissors")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
}//end pickWinner
The problem seems to be that when I called in getCPUChoice or getUserChoice it would rerun the program and then change the final answers.
You calling getUserChoice() in the pickWinner method. It should be the userChoice method parameter you should be checking.
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (userChoice.equalsIgnoreCase("rock")) {
if (cpuChoice.equalsIgnoreCase("rock")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("paper")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (userChoice.equalsIgnoreCase("paper")){
if (cpuChoice.equalsIgnoreCase("paper")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "User";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (userChoice.equalsIgnoreCase("Scissors")){
if (cpuChoice.equalsIgnoreCase("scissors")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
You should ask for user input in each loop and not just once.
public class RockPaperScissors {
public String getUserChoice() {
Scanner sc = new Scanner (System.in);
System.out.println("Enter your choice:");
//not here
String userInput;
while (true){
//this is the right place
userInput = sc.nextLine();
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
break;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
}
}
return userInput;
}// end getUsechoice
//...
}//end rockPaperScissors
try changing this in your else part
userInput = sc.next();
to this
userInput = sc.nextLine();
So it will go to next line
So the resulting code ll be
while (end == true){
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
end = false;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
userInput = sc.nextLine();
}
}
Related
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");
}
}
The errors I am getting are "answer cannot be resolved". 1/4th of the way down the page. Looked online still don't see what it should be. Would it be easier to use the while loop instead? skipping the do loop completely?
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
// do loop begining
do
{
computerHand = computerHand();
userHand = userHand();
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.print("User picks" + userHand );
System.out.println("Computer picks " + computerHand );
System.out.println("play again?");
String answer = tnt.next();
//Condition for the do-while loop HERE IS THE ERROR LOCATION
}while (!answer.Equals("No") && (!answer.Equals("no"))); //condition for while loop
String answer = tnt.next();
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println("Lets play rock paper scissors");
System.out.println("1. Rock ");
System.out.println("2. Paper ");
System.out.println("3. Scissors ");
int userChoice; // user choice variable in this method
Scanner tnt = new Scanner(System.in); // creates instance of scanner class
userChoice = tnt.nextInt(); //reads user input
return getChoice(userChoice); //returns user choice to master choice
}
public static String computerHand() //method for computer generated choice
{
int computernum = (int)(Math.random() * (( 3) + 1));
return getChoice(computernum);
}
public static String getChoice(int num) //method recieving both computer hand and user hand
{
// if statements to place the correct choice
String choice = "";
if (num == 1){
choice = "rock";
}
else if(num == 2){
choice = "paper";
}
else if(num == 3){
choice = "scissors";
}
return choice;
}
// Method determing the winner
public static String getWinner(String computerChoice, String userChoice)
{
computerChoice = computerHand(); //places computerChoice variable in computerhand
userChoice = userHand(); //does same for user choice
String winner="";
System.out.println( " the comp chose" + computerChoice);
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer"); }
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
}
if (userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
}
return winner;
}
}
Use tnt.next() which returns the next string. there is no such thing as nextString().
Also, add return winner; at the end of getwinner method.
You declared answer inside the braces of your do and then tried to use it outside the braces. Once you left the braces, the variable was out of scope.
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.
I asked this question before, but I think that because i only included as piece of the code it was unclear. I am writing a program that asks the user what kind of question they want asked, and then they are prompted for an answer to that question. However, even the correct input from the user results in a return of an incorrect answer. Here's the code:
import java.util.Scanner;
public class MascotQuiz {
public static void main(String[] args) {
int score = 0;
String greeting = "In this game, I ask you four questions about mascots for "
+ "US collegiate sports teams."
+ "\nYou get 1 point for each correct answer, "
+ "0 points if you type don't know, "
+ "and you lose a point for wrong answers.";
final String schoolOptions = "University of Michigan, "
+ "University of Nebraska, " + "University of Oklahoma, "
+ "University of Wisconsin";
final String mascotOptions = "Badgers, Cornhuskers, Sooners, Wolverines";
String prompt1 = "\nType 1 and I'll give you the mascot and "
+ "you give give the school. \n"
+ "Type 2 and I'll give you the school and "
+ "you give me the mascot. \n" + "Type 3 and I'll quit.";
System.out.println(greeting);
int questionCount = 1;
String mascotQuestion1, mascotQuestion2, mascotQuestion3, mascotQuestion4;
String schoolQuestion1, schoolQuestion2, schoolQuestion3, schoolQuestion4;
do {
System.out.println(prompt1);
int optionChoice;
Scanner scan = new Scanner(System.in);
optionChoice = scan.nextInt();
if (optionChoice == 1) {
if (questionCount == 1) {
System.out.println("What school do the Badgers belong to?");
mascotQuestion1 = scan.nextLine();
if (mascotQuestion1.equalsIgnoreCase("University of Michigan")) {
score++;
}
else if (mascotQuestion1.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
else if (questionCount == 2) {
System.out.println("What school do the Cornhuskers belong to?");
mascotQuestion2 = scan.next();
if (mascotQuestion2.equalsIgnoreCase("University of Nebrasksa")) {
score++;
}
else if (mascotQuestion2.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
else if (questionCount == 3) {
System.out.println("What school do the Sooners belong to?");
mascotQuestion3 = scan.next();
if (mascotQuestion3.equalsIgnoreCase("University of Oklahoma")) {
score++;
}
else if (mascotQuestion3.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
else {
System.out.println("What school do the Wolverines belong to?");
mascotQuestion4 = scan.next();
if (mascotQuestion4.equalsIgnoreCase("University of Winsconsin")) {
score++;
}
else if (mascotQuestion4.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
}
else if (optionChoice == 2) {
if (questionCount == 1) {
System.out.println("What mascot belongs to the University of Michigan?");
schoolQuestion1 = scan.next();
if (schoolQuestion1.equalsIgnoreCase("Badgers")){
score++;
}
else if (schoolQuestion1.equalsIgnoreCase("don't know")){
score = score + 0;
}
else {
score --;
}
}
else if (questionCount == 2) {
System.out.println("What mascot belongs to the University of Nebraska?");
schoolQuestion2 = scan.next();
if (schoolQuestion2.equalsIgnoreCase("Cornhuskers")){
score++;
}
else if (schoolQuestion2.equalsIgnoreCase("don't know")){
score = score + 0;
}
else {
score --;
}
}
else if (questionCount == 3) {
System.out.println("What mascot belongs to the University of Oklahoma?");
schoolQuestion3 = scan.next();
if (schoolQuestion3.equalsIgnoreCase("Sooners")){
score++;
}
else if (schoolQuestion3.equalsIgnoreCase("don't know")){
score = score + 0;
}
else {
score --;
}
}
else {
System.out.println("What mascot belongs to the University of Wisconsin?");
schoolQuestion4 = scan.next();
if (schoolQuestion4.equalsIgnoreCase("Wolverines")){
score++;
}
else if (schoolQuestion4.equalsIgnoreCase("don't know")){
score = score + 0;
}
else {
score --;
}
}
}
else {
questionCount = 5;
}
questionCount ++;
} while (questionCount <= 4);
System.out.println("\nBye. Your score is " + score);
}
}
I think your code is not taking the user answers correctly,it is just prompting the question and immediately print your prompt1 again and not giving the chance for answer. That's why it is not matching your answer and just going in the else loop where your score get decrease.
Another thing in your each if/ else statement you are using scan.next() that's why it is just reading only one word not a line.
I just make few changes in your code and it is running. I made few change in your if else condition do the same with others. I hope it will work for you -
Scanner scan ; // declare scanner reference here and use later
do {
System.out.println(prompt1);
int optionChoice;
scan = new Scanner(System.in); // create new scanner object
optionChoice = scan.nextInt();
if (optionChoice == 1) {
if (questionCount == 1) {
System.out.println("What school do the Badgers belong to?");
scan = new Scanner(System.in); // create new scanner object, it will allow user to enter answer
mascotQuestion1 = scan.nextLine(); // use nextline it will read full line otherwise it is just reading "university" not full answer
if (mascotQuestion1.equalsIgnoreCase("University of Michigan")) {
score++;
}
else if (mascotQuestion1.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
else if (questionCount == 2) {
System.out.println("What school do the Cornhuskers belong to?");
scan = new Scanner(System.in); // create new scanner object, it will allow user to enter answer
mascotQuestion2 = scan.nextLine();// use nextline it will read full line otherwise it is just reading "university" not full answer
if (mascotQuestion2.equalsIgnoreCase("University of Nebrasksa")) {
score++;
}
else if (mascotQuestion2.equalsIgnoreCase("don't know")) {
score = (score + 0);
System.out.println("score 2****----"+score);
}
else {
score--;
}
}
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!");
}
}