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 :)
Related
while(true)
{
switch (...)
{
case 1:
//some code
break;
case 2:
//some code
break;
}
System.out.println("(1)Continue (2)Exit");
//example:
int choice = scanner.nextInt();
if (choice == 1)
continue; //it should go to switch
else if (choice == 2)
{
System.out.println("Exit..."); // should exit
break;
}
else
{
System.out.println("Wrong num, try it again!"); // should ask choose again until we enter 1 or 2
//goto example;
}
}
My problem is: It goes to the beginning of the loop when I choose the wrong number. I want it to go to the part where the choose is asked (int choice = scanner.nextInt();) and asking again. "1" - > switch, "2" - > "exit" , "3" - > ask choice again.
Try like the below
while(true)
{
int choice = scanner.nextInt();
if (choice == 1)
continue;
else if (choice == 2)
{
System.out.println("Exit...");
break;
}
else
{
System.out.println("Wrong num, try it again!");
//goto example;
}
}
This should solve your problem.
import java.util.Scanner;
class Main
{
private static void switcher(int key)
{
switch (key)
{
case 1:
//some code
break;
case 2:
//some code
break;
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
switcher(0);//replace with whatever you need
System.out.println("(1)Continue (2)Exit");
while(true)
{
int choice = sc.nextInt();
if (choice == 1)
continue;
else if (choice == 2)
{
System.out.println("Exit...");
break;
}
else
{
System.out.println("Wrong num, try it again!");
}
switcher(0);//replace with whatever you need
}
}
}
If you have other requirements, please update your question.
You can try doing something like this, maybe a little ugly but I think it will work:
function get_choice(choice) {
if (choice == 1) {
// do something
} else if (choice == 2) {
// do something else
} else {
// something else
}
}
and then you just do something like get_choice(1);
try this approach:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int choice;
do {
System.out.println("Enter your choice :");
System.out.println("1. Start program");
System.out.println("2. End program");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
} while (choice != 2);
System.out.println("Exit application :");
}
}
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) {
...
}
The program is a standard flight database using OOP. In this main method there are 5 options that execute different tasks. Options 1 and 2 work without a problem, but for some reason options 3-5 don't execute. The code inside the if/else if's of options 3-5 do not run, and the program just outputs the main menu again.
boolean exit = false;
while (exit == false)
{
System.out.println("Now what would you like to do?");
System.out.println("1. Print out a flight's info");
System.out.println("2. Print out the number of flights through the static variable");
System.out.println("3. Change the departure time of a flight");
System.out.println("4. Change the departure gate of a flight");
System.out.println("5. Exit");
int choice = sc.nextInt();
if (choice == 1)
{
System.out.println("Which flight would you like to print (1 or 2)?");
int choice2 = sc.nextInt();
if (choice2 == 1)
{
f1.printFlight();
}
else if (choice2 == 2)
{
f2.printFlight();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 2)
{
System.out.println("This is the number of flights: ");
int numFlights = f1.getNumFlights();
System.out.println(numFlights);
}
else if (choice == 3)
{
System.out.println("Which flight would you like to change the departure time of (1 or 2)?");
int choice3 = sc.nextInt();
System.out.println(choice3);
if (choice3 == 1)
{
System.out.println("What is the new departure time for flight " + choice3);
int newTime = sc.nextInt();
f1.changeDeptTime(newTime);
}
else if (choice3 == 2)
{
f2.changeDeptTime();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 4)
{
System.out.println("Which flight would you like to change the departure gate of (1 or 2)?");
int choice4 = sc.nextInt();
if (choice4 == 1)
{
f1.changeDeptGate();
}
else if (choice4 == 2)
{
f2.changeDeptGate();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 5)
{
System.out.println("Exit Reached");
exit = true;
}
}
Use switch() statement for the choices for each case. Like
switch(x) {
case 1:
doSomething1();
case 2:
doSomething2();
case 3:
doSomething3();
}
How will I go about restarting the app if the user asks so.
Here is my code:
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
}
else if (restart != 1){
System.out.println("Goodbye..");
}
so if user press 1, the app restarts.. How can i create this?
Your application sounds like a loop, so lets use one.
/* #return true if should restart */
boolean run() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
return true;
}
else if (restart != 1){
System.out.println("Goodbye..");
return false;
}
}
while (run());
But this is Java, so you might as well do it more object oriented.
public class MyRestartable {
private boolean shouldRestart = true;
public void run() {
while(this.shouldRestart) {
start();
}
System.out.println("Goodbye..");
}
boolean start() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
this.shouldRestart = sc.nextInt();
}
}
Oh the joys of object based programming.
void start() {
System.out.println("Restart?");
System.out.println("Press 1: Restart");
System.out.println("Press 2: Finish");
int restart = sc.nextInt();
if(restart == 1){
***start();***
}
else if (restart != 1){
System.out.println("Goodbye..");
}
Use a while loop, and at the point you want to send the user back to the beginning, use the break; command enclosed in an if statement to decide whether the user is sent back or continues.
A simple while loop would work.
public static void Loop(){
Scanner input = new Scanner(System.in);
int loop = 1;
while(loop == 1){
System.out.println("Would you like to restart?");
System.out.println("Press 1 = yes");
System.out.println("Press 2 = no");
loop = input.nextInt();
}
}
I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}