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 5 years ago.
if (sum < 6) {
System.out.println("You win");
System.out.println();
// Does the user want to retry?
System.out.print("Would you like to retry?(Y or N) : ");
String retry = input.nextLine();
while (true) {
// If they say y or Y, roll again
if (("y".equals(retry)) || ("Y".equals(retry))) {
roll();
// Check for anything other than y and Y
} else if (("n".equals(retry)) || ("N".equals(retry))) {
System.out.println("Closing");
break;
} else if (!("y".equals(retry)) || !("Y".equals(retry))) {
System.out.print("Invalid input. Would you like to retry?(Y or N) : ");
retry = input.nextLine();
System.out.println();
}
}
} else if (sum > 6) {
System.out.println("You lose");
System.out.println();
System.out.print("Would you like to retry?(Y or N) : ");
String retry = input.nextLine();
while (true) {
if (("y".equals(retry)) || ("Y".equals(retry))) {
roll();
} else if (("n".equals(retry)) || ("N".equals(retry))) {
System.out.println("Closing");
break;
} else if (!("y".equals(retry)) || !("Y".equals(retry))) {
System.out.print("Invalid input. Would you like to retry?(Y or N) : ");
retry = input.nextLine();
System.out.println();
}
}
}
I'm trying to make a dice game where the game will keep rolling the dices when the user inputs "y" or "Y". I also want it to stop the game and say "Closing" when the user inputs "n" or "N".
The issue is, when the user inputs "n" or "N", it will print out "Closing" but the loop doesn't stop and the game will roll the dices again. How to I make my while() loop stop when the user inputs "n" or "N"?
Here's the output when the user chooses to stop the game ("n" or "N") : Would
you like to retry?(Y or N) : n
Closing
Rolling...
You rolled : 1 & 4
Sum = 5
You win
I'm sorry for such basic question, I am new to programming.
Move the line String retry = input.nextLine(); into the while loop (in both if branches). Currently you read in one input and then compare that non-changing input over and over again.
Related
I am fully aware this question has been asked many times, it is a classic first year problem in CSC. I am not looking for the solution to the problem itself. I think I have it basically done however I am missing something that I cannot find how to do.
Here is my code:
import java.util.Scanner;
import java.util.Random;
public class HiLow
{
public static void main (String[] args)
{
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int num1,guess;
int count = 0;
num1 = generator.nextInt(100) + 1;
while(true) {
System.out.print("Enter an integer between 1 or 100 or enter 0 at anytime to quit: ");
guess = scan.nextInt();
count++;
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
break;
}
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
break;
}
else if (guess > 100 || guess < 1) {
System.out.print("I see you cannot follow instructions. I said ");
count--;
}
else if (guess > num1) {
System.out.println("You have guessed too high. ");
}
else {
System.out.println("You have guessed too low.");
}
}
}
}
My problem is i am required to prompt the user at the point of "if the user quits or successfully guesses the correct number, prompt the user to see if they wish to play again". I am lost and not sure how to continue my while loop from the beginning after my breaks. Is there a way to end the break condition i have from (guess == num1 || guess ==0) and direct my program to start again at the while(true) statement?
Thanks
I will say search up continue;
Tips to help further:
The continue statement is used to bring the loop back to the start, try it instead of a break where you want the user to continue.
You need some sort of check if the user wants to continue, (try asking them to type in some specific int you check, p.s negative numbers are integers as well)
#Ahmed thinks you should continue, I would rather not break, or conditionally break.
Well there are multiple ways you could accomplish this, One would be to just to prompt the user with a "press q to quit" dialogue using the Scanner class where .next() returns the String when the user hits enter:
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
}else{
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
}
System.out.println("would you like to play again [y/n]?");
if(scan.next().equals("y")){
num1 = generator.nextInt(100) + 1;
count=0;
}else{
break;
}
}
If thats what you mean. Hopefully I helped.
or maybe you can have it only quit at zero, if so just remove that second break and replace it with num1 = generator.nextInt(100) + 1; to set the new value to guess.
This question already has answers here:
How can I check for invalid input and loop until the input is valid?
(3 answers)
Closed 5 years ago.
I've made a street craps game and have an error checker in the beginning to make sure the input is valid, I put it in an if statement and then have the rest of the code (for valid inputs) as the else but it isn't recognizing the else part when the user puts in a valid number.
public void play() { //method
System.out.println("Please pick a number.");
guess = scan.nextInt();
if (guess == 7 || guess == 1 || guess == 0 || guess > 12) {
System.out.println("Sorry, that is an invalid input, please choose another number.");
guess = scan.nextInt();
} else {
int roll = dieOne.roll();
int roll2 = dieTwo.roll();
int rollSums = roll + roll2;
System.out.println(roll + "+" + roll2);
while (rollSums != 7) {
if (guess == rollSums) {
System.out.println("Congratulations, you win! Your number was rolled before a seven was rolled!");
rollSums = 7;
guess = 7;
} else {
roll = dieOne.roll();
roll2 = dieTwo.roll();
rollSums = roll + roll2;
System.out.println(roll + "+" + roll2);
}
}
if (rollSums != guess) {
System.out.println("Sorry, your number was not rolled before a seven was rolled.");
}
}
}
I guess you want to execute the if part until the if condition is not satisfied, and then you want to execute the else part. If this is what you want you need to execute the if part as a while loop, and the else part as code after the while loop.
You need a while loop to make sure you get a good input first, and then do the game logic, like this:
int guess = scan.nextInt();
while (guess == 7 || guess == 1 || guess == 0 || guess > 12){
System.out.println("Sorry, that is an invalid input, please choose another number.");
guess = scan.nextInt();
}
//Game Logic (Stuff in else section)
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I'm currently making a Tic Tac Toe game. when a player wins and is asked if they want to play again, I call the Playing(); method to restart the game. The issue I'm having is that it loops the Playing(); without stopping at the first Scanner.
How can I make the loop stop at the first Scanner (which asks the user to enter their [row]?
Output when A player agrees to restart :
Enter [Row] : Please enter a number :
Enter [Row] :
Playing() Method
public static void Playing() {
String line;
// Check if the user's input is a number. If not, retry!
while (true) {
try {
System.out.print("\nEnter [Row] : "); //Tell user to input Row
line = input.nextLine();
row = Integer.parseInt(line) - 1;
System.out.print("Enter [Col] : "); //Tell user to input Col
line = input.nextLine();
col = Integer.parseInt(line) - 1;
break;
} catch (NumberFormatException e) {
System.out.print("Please enter a number : ");
break;
}
}
//Check if their input for [row][col] is valid
if (row < 0 || row > 2 || col < 0 || col > 2) {
System.out.print("Oops! Invalid input. Try again");
Playing();
} else if (Board[row][col] != '_') {
System.out.print("This position is already taken. Try again");
Playing();
} else {
Board[row][col] = player;
moveCount++;
DisplayBoard();
GameOver(); //Check if anyone won. If not, continue the game
}
}
Replay() Method
public static void Replay() {
/*
* Check if the user wants to play again
*/
System.out.print("Would you like to play again?(Y or N) : ");
while (true) {
String retry = input.next();
if ("y".equalsIgnoreCase(retry)) {
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
Board[r][c] = '_';
}
}
System.out.print("-----------------------------------------------------\n");
DisplayBoard();
Playing();
break;
} else if ("n".equalsIgnoreCase(retry)) {
System.out.println("Thank you for Playing!");
System.exit(1);
// If the user enters an invalid input, this will ask them to try again
} else {
System.out.print("Invalid input. Would you like to play again?(Y or N) : ");
}
}
}
First of all, what is the reason for using
line = input.nextLine();
row = Integer.parseInt(line) - 1;
where one can actually get the integers using nextInt() method available from Scanner
line = input.nextInt();
row = line - 1;
And to answer your question, I think this is the culprit which causes to skip your inputs
String retry = input.next();
In this line if your enter some keyword, say "Hello" and hit enter which is "Hello\n" the next method only takes "Hello" and the \n will skip your nextLine() method. So I suggest you to try adding another nextLine() after this line
String retry = input.next();
input.nextLine();
Note: This is only a guess for a problem, I haven't actually debugged your code by running on my end-system.
I have two questions regarding my code.
Why does is the output "Oops please enter a number between 1 and 6" when I enter a number between 1 and 6. When I try to be more specific and make an else if statement, nothing happens when I enter a number NOT between 1 and 6.
How do I restart my program? In my code, there is an if statement
when the user inputs "play again" My commented out line reads
Mastermind.main() to re run the program, but that didn't work.
Here is the code:
import java.util.Scanner;
public class Mastermind {
public static void main (String [] args) {
// boolean variable to signal when the game is over.
boolean done = false;
// Scanner object
Scanner scanner = new Scanner(System.in);
// sets the value to twelve outside the loop so it doesn't set back each time.
int guesses = 12;
System.out.println("Please enter a number between 1-6 to begin (or \"quit\") to exit.");
// while loop for the game
while (!done) {
//System.out.println("Please enter a number between 1-6 (or \"quit\") to exit the game:");
// user input
String input = scanner.nextLine();
int number = 0; //Just initialized to some number
// checks to see if the user wants to quit the game.
if (input.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else{
try{
//Trying to see if the input was a number
number = Integer.parseInt(input);
}
catch(Exception e){
//The input wasn't an integer, it's invalid the starts loop again.
System.out.println("Invalid input.");
continue;
}
}
// defines necessary int variables
int random1 = (int) (Math.random() * 7);
int random2 = (int) (Math.random() * 7);
int random3 = (int) (Math.random() * 7);
int random4 = (int) (Math.random() * 7);
// If the user doesn't and decides to play, it runs this code.
// checks to see if the user enters a number between 1-6
if (number >= 1 && number <= 6) {
if (number == random1) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random2) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random3) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random4) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else {
System.out.println("Sorry that's not one of the numbers! Try again.");
guesses--;
System.out.println("guesses = " + guesses);
}
}
if (guesses == 0){
System.out.println("You've run out of guesses. To play again, enter \"play again\". Otherwise, enter or \"quit\")");
if (input.equalsIgnoreCase("play again")){
// how do I restart the program?
//Mastermind.main(); // QUESTION 2
}
else if (input.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
}
}
}
You're printing that message every time through the loop whenever guesses == 0 evaluates to false. You probably just need to switch the order of the two blocks. Instead of this:
if (number >= 1 && number <= 6) {
...
}
if (guesses == 0) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
Use this:
if (number >= 1 && number <= 6) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
if (guesses == 0) {
...
}
Regarding restarting your program: if I'm reading the logic correctly, all you need to do is keep done set to false and reset guesses to 12.
Two other logic points. First, you should probably either continue or break after detecting that the user has entered "quit". Second, it seems like you are generating four new random integers for every user guess. I don't know if that's what you intended, but you might want to change the logic a bit. That might also affect the restart logic.
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
In my program I'm trying to get a user to input an int between 1-3 and then do something based off what they type. If it is not a number or not one of the options then it will allow them to reenter a valid option.
The issue I have is I'm having trouble brainstorming how to not have it infinitely loop and just allow them to enter in a number after the console tells them they entered an invalid input.
int i = 0;
while (i < 1) {
try {
int level = scan.nextInt();
i+=1;
if (level == 1) {
System.out.println("You selected level 1!");
//Start the game
} else if (level == 2) {
System.out.println("You selected level 2!");
//Start the game
} else if (level == 3) {
System.out.println("You selected level 3!");
//Start the game
} else {
System.out.println("That's not an option!");
i-=1;
}
} catch(InputMismatchException input) {
System.out.println("That's not an option!");
i-=1;
}
}
When you input an invalid input, you need to clear it. Add scan.next() when input exception triggered so as to clear it with next():
catch(InputMismatchException input) {
System.out.println("That's not an option!");
scan.next();
i-=1;
}
Not quite the answer you were expecting, but: refactor this code. Remember the basics of java, where every functional bit has its own method. So use a method that reads the input, and returns the level selected (or -1 if nothing):
int readInput() {
// your code here, returning either the level or -1 on bad input
}
And then call that for your read loop:
int selected;
do {
selected = readInput();
} while(selected < 1);
You are better off writing the code like this:
while(true){
try{
int level = scan.nextInt();
if(level==1){
System.out.println("You selected level 1!");
break;
}else if(level==2){
System.out.println("You selected level 2!");
break;
}else if(level==3){
System.out.println("You selected level 3!");
break;
}else{
System.out.println("That's not an option!");
continue;
}
}catch(InputMismatchException input){
System.out.println("That's not an option!");
continue;
}
}
continue will immediately resume execution of the loop at the top, and break will immediately jump too the closing brace } of the while. This removes the use of the i counter variable, which was entirely useless to the code. Also, this code will never run indefinitely, unless the user indefinitely enters improper values!
Hope this helped, good luck!
You can proceed in a much simpler way. The 3 valid cases are very similar and can be treated as one, the game can be started only once after the loop because we know that once the loop exits, level has a valid value.
boolean valid = false;
int level;
do {
try {
level = scan.nextInt();
valid = 1 <= level && level <= 3;
if (valid) {
System.out.println(String.format("You selected level %d !",level));
} else {
System.out.println("That's not an option!");
}
} catch(InputMismatchException input) {
scan.next();
System.out.println("That's not an option!");
}
} while (!valid);
// start the game