Java play again? (y/n) [duplicate] - java

This question already has answers here:
How to use this boolean in an if statement?
(8 answers)
Closed 7 years ago.
import java.util.Scanner;
public class PlayAgain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean playing = true;
char replayCheck;
do { //start do-while
System.out.print("Play again? (y/n): ");
boolean validInput = false;
while (validInput = false){ //start while
replayCheck = input.next().charAt(0);
switch (replayCheck) { //start switch
case 'y':
case 'Y':
validInput = true;
playing = true;
break;
case 'n':
case 'N':
validInput = true;
playing = false;
break;
default:
System.out.println("Invalid input! please enter (y/n)");
validInput = false;
break;
} //end switch
} //end while
} while (playing = true); //end do-while
System.out.println("Thanks for playing!");
} //end main
} //end class
If the user enters n/N the program plays again, same goes for any other input. The logic seems just fine, but I get "the assigned value is never used" on the line with replayCheck = input.next().charAt(0); so I suspect the issue is there.
I'm a bit of a noobie. Any suggestions are welcome!

change '=' to '==' for comparison, and your code works fine :
import java.util.Scanner;
public class PlayAgain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean playing = true;
char replayCheck;
do { //start do-while
System.out.print("Play again? (y/n): ");
boolean validInput = false;
while (validInput == false){ //start while
replayCheck = input.next().charAt(0);
switch (replayCheck) { //start switch
case 'y':
case 'Y':
validInput = true;
playing = true;
break;
case 'n':
case 'N':
validInput = true;
playing = false;
break;
default:
System.out.println("Invalid input! please enter (y/n)");
validInput = false;
break;
} //end switch
} //end while
} while (playing == true); //end do-while
System.out.println("Thanks for playing!");
} //end main
} //end class

Problem is at while loop it should be
while (validInput == false) {}

The check needs to be:
while (validInput == false) {
....
}
Otherwise you'll assign false to validInput, which results in false and therefore quits the loop.
In Java, the idiomatic way to write such a check is:
while (!validInput) {
...
}

Related

Validate the input using a while loop

I doing a little practice on Computer Science because when I leave the military I want to start taking classes on the basics of java. I'm a little stuck on this question i was wondering if i can get some assistance.
a program that allows the user to enter a character. The only valid values are 'A', 'M', and 'S'. Validate the input using a while loop so that if the user enters any value other than one of those 3 characters, an error message is displayed and the user is prompted for another value. Once the user has finally entered valid data, print the character they entered back to the screen.
You can look into this basic example
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isCheck = true;
while (isCheck) {
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next");
isCheck = true;
}
}
}
}
Reading you input within the loop will enforce repetitive reading of input.
public class Read {
public static void main(String[] args) {
boolean isCheck = true;
while(isCheck){
Scanner sc = new Scanner(System.in);
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next.");
isCheck = true;
}
}
}
}

wrong value in while statement java

Fairly new to coding but I am struggling to find the issue in my code. It is just a class which will run a few other classes and ask if you want to play again or not.
The issue is when you choose the first game and then say n or no to not play again when you play a second game after answering that you would like to play again it goes back to asking what game you would play instead of repeating the game.
public static void arcade() {
Scanner scanner2 = new Scanner(System.in);
String choice;
int game;
boolean finish;
finish = false;
game = 0;
do {
try {
System.out.println(
"Which game would you like to play? \n1. Coin toss\n2. Rock Paper Scissors \n3. Number Game\n4. Exit");
game = scanner2.nextInt();
switch (game) {
case 1:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
coinToss(scanner2);
System.out.println("Would you like to play again?");
choice = scanner2.next();
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
choice = scanner2.next();
}
} while (finish != true);
break;
case 2:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
rockPaperScissors(scanner2);
System.out.println("Would you like to play again?");
choice = scanner2.next();
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
}
} while (finish != true);
break;
case 3:
choice = "yes";
do {
if (choice.equalsIgnoreCase("yes") || choice.equalsIgnoreCase("y")) {
numberGame(scanner2);
System.out.println("Would you like to play again?");
} else if (choice.equalsIgnoreCase("no") || choice.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
finish = true;
} else {
System.out.println("Invalid selection");
}
} while (finish != true);
break;
case 4:
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid selection");
}
} catch (java.util.InputMismatchException e) {
System.err.println("Please use numbers");
scanner2.nextLine();
}
} while (game != 4);
scanner2.close();
}
Your forgot to re-initialize every time the finish variable to false:
case 2:
choice = "yes";
do {
finish = false;
...
You should do it for every case. Consider also that in your 3rd switch you also forgot to scan for the input after asking "Would you like to play again?".
Finally try to refactor your code a bit :)

Loop back to program after an exception is thrown

public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
int Choice = 0;
do {
try {
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
Choice = Option.nextInt();
switch (Choice) { //used switch statement instead of If else because more effective
case 1:
CreateAccount();
break; //breaks iteration
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
System.out.println("Invalid Entry");
throw new Exception();
}
} catch (Exception e) {
System.err.println("Enter Correct Input");
return;
}
} while (true);
}
I am trying to make it when users enter incorrect input type like a letter , the exception is caught and then returns back to the menus, right now it catches the exception but it doesnt stop running I have to force stop the program. So I added a return but that just displays the exception error and stops, how can I make it return back to the menus?
That is because you're returning from the method itself in the catch block.
And Do not throw exceptions like that. Just use some boolean to know if the choice is valid and loop until the choice is entered correctly.Prefer not to use while(true), instead rely on a boolean flag everytime like below,
public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
int Choice = 0;
boolean isValidChoice = false;
do{
isValidChoice = false;
Choice = 0;
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
if(Option.hasNextInt()){
Choice= Option.nextInt();
isValidChoice = true;
}
switch (Choice)
{
case 1:
CreateAccount();
break;
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
isValidChoice = false; //if invalid choice, then set flag to loop
System.out.println("Invalid Entry");
}
} while (!isValidChoice);
}
Move the "try {" after the "System.out.println("Please choose");" line.
you just need to remove the return in the catch. also just as a tip, you can get rid of the do while and just have a while loop, because the loop is never ending.
} catch (Exception e) {
System.err.println("Enter Correct Input");
}
Okay so I'm pretty sure this should work:
Create a boolean value outside of while loop that is holds if there was a valid input
boolean validInput = true;
In default set this value to false (meaning there is an invalid input)
default:
System.out.println("Invalid Entry");
validInput = false;
throw new Exception();
Make sure the catch statement is still in the do loop because the throw clause will halt normal execution and transition into exception execution. Next the while tester will test if there was a valid input
while(!validInput)
Lastly go up to the top of the do loop and set validInput to true. This will make it so that each time you clear the previous incorrect input.
This should work.

Java hardcoded repeating process

I am making a basic hardcoded game that has 2 users that will fight each other. All my methods are set and work as expected. I am now trying to figure out a way after looping through the main hardcode, to give the option to fight again and continue the game, instead of just stopping after 1 fight.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("What is your name: ");
String myName = in.nextLine();
Fighter a = new Warrior();
Fighter b = new Dragon();
a.pickOpponent(b);
a.setName(myName);
b.setName("Onyxia");
System.out.print(getWelcome());
while(in.hasNextLine())
{
switch(in.nextLine())
{
case "no":
System.out.println("Wow, you are not even gonna try, you have lost!");
break;
case "yes":
System.out.println("Let the fight begin! ");
while(a.isAlive() && b.isAlive())
{
System.out.println("Do you want to punch, kick, or headbutt the other fighter? ");
switch(in.nextLine())
{
case "punch":
System.out.println(a.getPunch(b));
System.out.println(b.getOpponentAttack(a));
break;
case "kick":
System.out.println(a.getKick(b));
System.out.println(b.getOpponentAttack(a));
break;
case "headbutt":
System.out.println(a.getHeadbutt(b));
System.out.println(b.getOpponentAttack(a));
break;
default :
System.out.println(invalidInput());
break;
}
}
default:
System.out.println(a.getWinner(b));
break;
}//end of first switch statement
}//end of first while loop
}//end of main
Try moving all of the code in main into a new function.
You can put that function into a while loop in your main method, like so:
while(playGame()) {}
and have playGame() return true if the came should be played again, and false if it should end.
Sample:
public static boolean playGame() {
Scanner in = new Scanner(System.in);
System.out.print("What is your name: ");
String myName = in.nextLine();
Fighter a = new Warrior();
Fighter b = new Dragon();
a.pickOpponent(b);
a.setName(myName);
b.setName("Onyxia");
System.out.print(getWelcome());
while(in.hasNextLine())
{
switch(in.nextLine())
{
case "no":
System.out.println("Wow, you are not even gonna try, you have lost!");
break;
case "yes":
System.out.println("Let the fight begin! ");
while(a.isAlive() && b.isAlive())
{
System.out.println("Do you want to punch, kick, or headbutt the other fighter? ");
switch(in.nextLine())
{
case "punch":
System.out.println(a.getPunch(b));
System.out.println(b.getOpponentAttack(a));
break;
case "kick":
System.out.println(a.getKick(b));
System.out.println(b.getOpponentAttack(a));
break;
case "headbutt":
System.out.println(a.getHeadbutt(b));
System.out.println(b.getOpponentAttack(a));
break;
default :
System.out.println(invalidInput());
break;
}
}
default:
System.out.println(a.getWinner(b));
break;
}//end of first switch statement
}//end of first while loop
}//end of playGame
public static void main(String[] args) {
while(playGame()) {}
}
I'd put while(true) above System.out.print(getWelcome()); and closing it right before you close main. Then you can ask the user something like
System.out.println("Dare yie try again?");
String answer = in.nextLine();
if(answer.equals("yes"))
break; //which would break out of the while loop.

Java: I can't get it to loop, somethings wrong with the boolean but I don't know how to fix it

public class Main {
public static void main(String[] args)throws Exception {
Boolean yn;
String answer;
String name;
do{
Scanner in = new Scanner(System.in);
System.out.println("Enter your name");
name = in.nextLine();
System.out.println("Hi "+name);
System.out.println("Do you want to enter another name?");
System.out.println("y/n?");
answer = in.nextLine().toLowerCase();
if(answer.equals("y")){
yn = true;
break;
}else if(answer.equals("n")){
yn = false;
break;
}
}while(yn = true );
}
}
i have to make it go back to asking the name when i get a yes for the last question.
super noob here sorry please help.
Your break is the culprit...
When you use break it breaks out of the loop.
So use, (Note: You don't need an else if, just else should be sufficient).
if(answer.equals("y")){
yn = true;
} else {
yn = false;
}
without break statement.
Also use a condition (not assignment) inside while,
while(yn == true)
or simply,
while(yn)
The break should not be used in an if statement only if you want to close the loop, remove break from if.
You can do this :
public static void main(String[] args)throws Exception {
Boolean yn;
String answer;
String name;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your name");
name = in.nextLine();
System.out.println("Hi "+name);
System.out.println("Do you want to enter another name?");
System.out.println("y/n?");
answer = in.nextLine().toLowerCase();
if(answer.equals("y")){
yn = true;
continue; //Continue does not terminate the loop instead of break
}else {
yn = false;
break;
}
}while(yn = true );
}
use continue instead of break as below
if(answer.equals("y")){
yn = true;
break; //use continue here
} else if(answer.equals("n")){
yn = false;
break;
}

Categories

Resources