Heads or Tails Game - Loop Issues - java

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!");
}
}

Related

Java replay when certain character typed

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;
}

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;
}

Need to stop two loops from looping within a loop

So my program asks two questions, directions and miles. A user can enter an infinite input for direction and miles, but once the user is done he would simply type "Done" and the loop would break and show the message and the end. I can't get the loops to break need help. Also when a letter is typed for numOfMiles the program just ends. It's suppose to give the error message and reprompt but i can't seem to get that working.
import javax.swing.JOptionPane;
public class taxiService {
public static void main(String [] args) {
//Declare variables
double fareCharge = 5;
double totalMiles = 0;
double finalFareCharged = 0;
double finalxCoord = 0;
double finalyCoord = 0;
double numOfMiles = 0;
double finalCoord = 0;
String error = "Invalid data, please enter valid data!";
String directions = "";
boolean restart = true;
//Prompt for direction and miles
while(restart){
boolean reprompt = true;
boolean reprompt_SecondQuestion = true;
while (reprompt) {
directions = JOptionPane.showInputDialog(null, "Please enter a direction: ");
if (directions.equalsIgnoreCase("East")) {
finalxCoord = finalxCoord + numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("West")) {
finalxCoord = finalxCoord - numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("North")) {
finalyCoord = finalyCoord + numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("South")) {
finalyCoord = finalyCoord - numOfMiles;
reprompt = false;
}
else {
reprompt = true;
JOptionPane.showMessageDialog(null, error);
}
}
while(reprompt_SecondQuestion)
{
numOfMiles = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter distance in miles: "));
if (numOfMiles > 0) {
totalMiles += numOfMiles;
reprompt_SecondQuestion = false;
}
else {
JOptionPane.showMessageDialog(null, error);
}
}
//Prompt user to type "done"
//Capture user input
if(directions.equalsIgnoreCase("Done"))
{
//Display direction and miles to user
restart = false;
break;
}
else
{
}
}
finalFareCharged = fareCharge + ((numOfMiles / .25) * 2);
JOptionPane.showMessageDialog(null, "miles: " + totalMiles + "\nDirection :" + directions + "\nFinal Charge: " + finalFareCharged + "\nCoordination: " + finalCoord);
}
}
I was able to use this to stop the looping problem
while(done) {
end = JOptionPane.showInputDialog(null, "Is this your destination?(YES/NO)");
if (end.equalsIgnoreCase("Yes")) {
restart = false;
reprompt = false;
reprompt_SecondQuestion = false;
done = false;
break;
}
else if (end.equalsIgnoreCase("No")) {
restart = true;
done = false;
}
else{
JOptionPane.showMessageDialog(null, error);
done = true;
}
}
i still got a problem with numOfMiles. if a letter is entered the program ends. it doesn't give the error message. i've added reprompt_SecondQestion = true; but no change.
I would use labeled break statement (so the intention would be clear for the future reader of the code). Here is the example which prints s0-1-2-3e:
...
System.out.print("s");
labelName:
while (true) {
for (int i = 0; i < 5; i++) {
System.out.print(i);
if (i == 3) {
break labelName; // the "thing" you are looking for
}
}
System.out.print("-");
}
System.out.print("e");
...
This means that you only need to add the label label: and condition statement:
if (directions.equalsIgnoreCase("Done")) {
break label;
}
Your task now, is just to find a proper places to put the code.
Check the condition of your loop. Something like this would suffice:
if(directions.equalsIgnoreCase("Done"))
{
//Display direction and miles to user
reprompt_SecondQuestion = false;
reprompt = false;
restart = false;
break;
}
Also I cannot tell from the brackets where this block is located, if it is at all within the loop. Please check, as proper formatting will save you hours.

Having issues with methods

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();
}
}

A method in my java program first skips user input then asks for it once it calls itself [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
Here is the particular function I am having trouble with.
static boolean check(double money)
{
String scont, yes = "yes", no = "no";
boolean bcont;
if (money == 0) {
System.out.println("You are broke and can no longer play.");
bcont = false;
return bcont;
}
System.out.println("You have " + form.format(money) + " left.");
System.out.println("Would you like to continue playing? (Yes or no?)");
scont = in.nextLine();
if (scont.equalsIgnoreCase(yes)) {
bcont = true;
return bcont;
}
else if (scont.equalsIgnoreCase(no)) {
bcont = false;
return bcont;
}
else {
System.out.println("Invalid answer.");
bcont = check(money);
return bcont;
}
}
Here is the whole program.
import java.util.Random;
import java.util.Scanner;
import java.text.*;
public class JS4B
{
static Scanner in = new Scanner(System.in);
static DecimalFormat form = new DecimalFormat("$#.00");
public static void main(String [] args)
{
int roundnum = 1;
double beginmoney, money;
boolean cont;
intro();
beginmoney = hmmoney();
money = beginmoney;
do{
System.out.println("\nRound " + roundnum + ":");
System.out.println("-------\n");
money = round(money);
cont = check(money);
}while(cont == true);
if (money > beginmoney) {
System.out.println("Congratulations! You have completed " +
rounds(roundnum) + " and ended up with more money than you started!");
}
else if (money == beginmoney) {
System.out.println("You broke even! You have completed " +
rounds(roundnum) + ".");
}
else if (money != 0) {
System.out.println("You have less money than you started with, but " +
"at least you didn't lose it all. You completed " + rounds(roundnum) + ".");
}
else {
System.out.println("You have completed " + rounds(roundnum) + ".");
}
System.out.println("You started with " + form.format(beginmoney) +
" and ended with " + form.format(money));
}
static void intro()
{
System.out.println(" Guess the Number! ");
System.out.println("===========================");
System.out.println("In this game, a random \n" +
"number between 1 and 100 \n" +
"will be chosen. You have to \n" +
"guess what it is in 4 tries.\n");
}
static double hmmoney()
{
double money;
System.out.print("How much money would you like to start with?\nI would like" +
" to start with... ");
money = in.nextDouble();
System.out.println("");
return money;
}
static double round(double money)
{
int guess, actual, guessnum = 1;
double bet = bet(money);
boolean correct;
actual = genint();
for (;;)
{
guess = guess();
correct = check(guess, actual);
if (correct == false) {
guessnum++;
if (guessnum > 4) {
System.out.println("You have made the max number of guesses " +
"and have lost this round.");
System.out.println("The correct number was... " + actual + "\n");
money -= bet;
break;
}
else {
hint(guess, actual);
}
}
else {
money += bet;
break;
}
}
return money;
}
static double bet(double money)
{
double bet;
System.out.print("How much money would you like to bet? ");
bet = in.nextDouble();
System.out.println("");
if (bet > money) {
System.out.println("You can't bet more than you have!");
bet = bet(money);
}
return bet;
}
static int genint()
{
Random gen = new Random();
int actual;
actual = gen.nextInt(100) + 1;
return actual;
}
static int guess()
{
int guess;
System.out.print("I think that the number is... ");
guess = in.nextInt();
System.out.println("");
return guess;
}
static boolean check(int guess, int actual)
{
if (guess != actual) {
System.out.println("That is incorrect.");
return false;
}
else {
System.out.println("Congratulations! You guessed the correct number!");
return true;
}
}
static boolean check(double money)
{
String scont, yes = "yes", no = "no";
boolean bcont;
if (money == 0) {
System.out.println("You are broke and can no longer play.");
bcont = false;
return bcont;
}
System.out.println("You have " + form.format(money) + " left.");
System.out.println("Would you like to continue playing? (Yes or no?)");
scont = System.in.readline();
if (scont.equalsIgnoreCase(yes)) {
bcont = true;
return bcont;
}
else if (scont.equalsIgnoreCase(no)) {
bcont = false;
return bcont;
}
else {
System.out.println("Invalid answer.");
bcont = check(money);
return bcont;
}
}
static void hint(int guess, int actual)
{
if (guess > actual) {
System.out.println("Guess lower!");
}
else {
System.out.println("Guess higher!");
}
}
static String rounds(int roundnum)
{
String result;
if (roundnum == 1) {
result = "1 Round";
return result;
}
else {
result = Integer.toString(roundnum) + " Rounds";
return result;
}
}
}
By the way, this is for my AP Java class, that's why the program is what it is.
In that function, it will bypass the user input and go right to the else statement after it. Then, it will call itself and will take user input after that.
So, in this part of the code:
do{
System.out.println("\nRound " + roundnum + ":");
System.out.println("-------\n");
money = round(money);
cont = check(money);
}while(cont == true);
round() and check() are both functions which use the Scanner object that is declared as a field in your class. round() uses nextInt(), while check() uses nextLine().
What's happening is that when round() is parsing out the guesses, nextInt() doesn't parse out any trailing whitespace after the number input (like a newline from pressing Enter). So, when you call check(), there's still a line for it to read in, and so when you hit this line
scont = in.nextLine();
it reads in that line instead, and since it's obviously not equal to "yes" or "no", it goes to the else block, where it then calls itself.
Since this is for class, I won't actually say how to fix this.
You can not have in the else section:
System.out.println("Invalid answer.");
bcont = check(money);
return bcont;
...because you are unnecessarily making a recursive call, which I am sure that's not what you want.
Hence, do something like this instead:
scont = System.in.readline();
do {
scont = System.in.readline();
if (scont.equalsIgnoreCase(yes)) {
bcont = true;
return bcont;
} else if (scont.equalsIgnoreCase(no)) {
bcont = false;
return bcont;
} else {
System.out.println("Invalid answer. Please try again. Would you like to continue playing? (Yes or no?)");
scont = System.in.readline();
} while (!scont.equalsIgnoreCase(yes) && !scont.equalsIgnoreCase(yes));
I recently had a similar problem working with the Scanner, and as Dennis explained, I'm pretty sure it has something to do with previous uses of the Scanner in the execution. Here is a link the question I posted about it.
Try/Catch inside While in static main method
Take a look at some of the answers given there. There's one in particular which visually explains how the Scanner does it's thing which I learned a lot from.

Categories

Resources