I'm trying to loop these two questions("please enter direction") AND ("Please enter distance in miles"). If incorrect value is inputed then it will reprompt the user to enter a correct value. So these two questions will loop until the user is done entering and a "Destination" is reached. I got the first question to loop if the user doesn't type north east south or west, but the second question I could only make it loop on itself.
boolean reprompt = true;
//Prompt for direction and miles
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);
}
}
numOfMiles = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter distance in miles: "));
if (numOfMiles > 0) {
totalMiles += numOfMiles;
JOptionPane.showMessageDialog(null, "miles: " + totalMiles);
}
else
JOptionPane.showMessageDialog(null, error);
Just make the second question inside a while loop with another boolean just as you did for the first question.
Code:
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;
JOptionPane.showMessageDialog(null, "miles: " + totalMiles);
reprompt_SecondQuestion = false;
}
else
{
JOptionPane.showMessageDialog(null, error);
}
}
//Prompt user to type "done"
//Capture user input
if(user_input.equals("Done"))
{
//Display direction and miles to user
restart = false;
}
else
{
}
}
Related
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;
}
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.
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();
}
}
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!");
}
}