I’m writing a small program that is asking that user to guess a number between 1 and 100. My idea was to make several methods one with game playGame(), one that shows menu showMenu(), one for statistic. I placed the menu inside a while loop in the main method hoping that every time a game is played it will the menu and ask the user for input. Most of it works fine buy I can’t get the program flow right.
Every time I finish a game, a new game starts. I think that the problem is in the while loop inside the many method. It works fine if I change:
public static void showMenu() {
Scanner input = new Scanner(System.in);
System.out.println("1. Play a game.");
System.out.println("2 Show statistics.");
System.out.println("3. Exit.\n");
System.out.println("Make a choise: ");
int selectMenu = input.nextInt();
while (true) {
switch (selectMenu) {
case 1:
playGame();
break;
case 2:
statistics();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Enter valid number:");
}
}
} //end showMenu
To:
public static void showMenu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("1. Play a game.");
System.out.println("2 Show statistics.");
System.out.println("3. Exit.\n");
System.out.println("Make a choise: ");
int selectMenu = input.nextInt();
switch (selectMenu) {
case 1:
playGame();
break;
case 2:
statistics();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Enter valid number:");
}
}
} //end showMenu
But I can’t understand why. In the firs example after the game is played a new game starts without showing the menu. It jumps directly to case: 1
Thanks a lot!
You can see the program below:
public class GuessTheNumber {
private static int gameCount;
private static int guessCount;
private static int highestNumber;
private static int lowestNumber;
public static void main(String[] args) {
while (true) {
showMenu();
}
} // end main
public static void playGame() {
int secretNumber, guess;
Scanner input = new Scanner(System.in);
SecureRandom rand = new SecureRandom();
secretNumber = rand.nextInt(100) + 1; //makes random number between 1 and 100
System.out.println(secretNumber);
System.out.println("Guess the secret mumber which is between 1 and 100.");
System.out.print("Make your guess: ");
guess = input.nextInt();
guessCount++;
highestNumber = guess;
lowestNumber = guess;
while (guess != secretNumber) {
// high or low logic
if (guess > secretNumber) {
System.out.println("The number is too high.");
}
else {
if (guess < secretNumber) {
System.out.println("The number is too low.");
}
}
System.out.print("Make a new guess: ");
guess = input.nextInt();
guessCount++;
//get highest and lowest number
if (guess > highestNumber) {
highestNumber = guess;
}
if (guess < lowestNumber) {
lowestNumber = guess;
}
} //end while
System.out.printf("Very good the right number was: %d%n", guess);
} //end playGame()
public static void showMenu() {
Scanner input = new Scanner(System.in);
System.out.println("1. Play a game.");
System.out.println("2 Show statistics.");
System.out.println("3. Exit.\n");
System.out.println("Make a choise: ");
int selectMenu = input.nextInt();
while (true) {
switch (selectMenu) {
case 1:
playGame();
break;
case 2:
statistics();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Enter valid number:");
}
}
} //end showMenu
public static void statistics() {
System.out.println("Games played: " + gameCount);
System.out.println("Total number of guesses: " + guessCount);
System.out.println("The highest number: " + highestNumber);
System.out.println("The lowest number: " + lowestNumber);
}
} //end class GuessTheNumber
As this seems like a homework project, here is a quick tip for finding loop issues - simply add System.out.println("") checks inside and outside of all loop and logic conditions.
EG). System.out.println("Before While True);
System.out.println("Inside Case 1");
System.out.println("Inside Case 2");
You will save yourself a ton of time as you'll be able to tell where your logic is breaking.
As a hint, take a look at int selectMenu = input.nextInt();. I would recommend printing the value of selectMenu using my advice above. You might be surprised to see what's assigned there.
Related
Hello there fellow coders. Just a noob here that is currently stuck in a pickle.
I am coding a math training program, and am needing to loop back to my main menu.
There is an infinite loop i am having trouble getting out of. If the user keeps answering the correct answer, it just keeps on asking for another problem. Selecting yes will generate a new answer and will keep doing so (infinite). Selecting no will terminate the program.
How do i make is so if they select no, it takes the user back to the main menu?
Also, how to make it so if they select yes, the problem only loops a new equation at max 10 times before taking the user back to my main menu.
This is my Code:
import java.util.Scanner;
import java.util.Random;
public class MathPracticeProgram
{
public static void main(String[] args)
{
//Scenario: Make a practice program for Addition, Subtraction, Multiplication, and Division. Include exit option as well.
Random rand = new Random ();
Scanner scan = new Scanner (System.in);
int menu = (5);
int num1, num2, user_answer, total;
System.out.println("Math Practice Porgram");
System.out.println("Please Input Your Choice via the number\n");
System.out.println("1. Addition\n2. Subtraction\n 3. Multiplication\n 4. Division\n Exit Program by entering 0");
System.out.println("\nYour choice:");
menu = scan.nextInt();
System.out.println("\n");
//Menu Selection
if (menu <= 5 || menu > 0)
{
switch(menu)
{
//Exit
case 0:
{
System.out.println("Thank you for using my math practice program.");
}
break;
//Addition
case 1:
{
System.out.println("You have selected Addition");
String user_again;
do
{
num1 = rand.nextInt(99);
num2 = rand.nextInt(99);
int counter = 0;
do
{
System.out.println("New solution to solve: ");
System.out.println(num1 + " + " + num2 + " = ");
user_answer = scan.nextInt();
System.out.println("\n");
total = num1 + num2;
if(user_answer != total)
{
System.out.println("Incorrect...");
counter++;
}
}while (user_answer != total && counter < 3);
System.out.println("Correct! Do you want another problem? yes or no: ");
user_again = scan.next();
}while(user_again.equalsIgnoreCase("yes"));
System.out.println("\nChanging to Main Menu\n");
}
break;
//Subtraction
case 2:
{
}
break;
//Multiplication
case 3:
{
System.out.println("Multiplication");
}
break;
//Division
case 4:
{
System.out.println("Division");
}
break;
}
}
}
}
When I compile, that try to enter (y) to play again my do - while is not working, it takes me out of the loop.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
int guessNumber = 0;
do
{
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Change the code as below: (You just need to update the variables inside the loop)
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = 0;
int guessNumber = 0;
do
{
// new lines to be added
theNumber = (int)(Math.random() * 100 + 1);
guessNumber = 0;
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
Here is the execution of code on Jshell:
The reason the program is not working is because the do-while loop does one iteration before it gets to the "while" part. In your case, the program successfully finishes the loop after a user correctly guesses the number. Your program breaks because after that you are requiring the user to enter 'y' to continue endlessly without letting them guess a number. If they guess a number, the program terminates.
I'm trying to code simple calculator (all in one) using Switch cases in java. I came up with following code so far. However I'm stuck with while loop. I want to keep showing main menu after each case execution until user decides to exit the program.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result=0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is "+result);
}
}
Above code works fine. Program ends itself after execution of user selected choice. I want to put main menu on a repeat.
Add a while loop like this:
public static void main(String[] args) {
// Moved this outside the while loop as davidxxx pointed out +1
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i = s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;//'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is " + result);
System.out.println("Go again?");
String goAgain = s.next();
if (!goAgain.equals("y")) {
break;
}
}
}
Try this:
import java.util.Scanner;
public class Calculator {
private static final String EXIT = "EXIT";
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner s = new Scanner(System.in);
while (true) {
String res = calc.runCalc(s);
if (res.equals(EXIT)) {
break;
} else {
System.out.println(res);
}
}
}
private String runCalc(Scanner s) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int i = s.nextInt();
if (i == 5) {
return EXIT;
}
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;// 'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
return "Wrong Choice.";
}
return "Answer is " + result;
}
}
There is more than one way to achieve this, you can use
while loop.
do-while loop.
for loop.
I think do-while loop is better for your situation. Because either user wants to continue or not you have to proceed one time(before loop false). And you do not want to use another variable for quit the loop.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int result=0;
do{
System.out.println("Main Menu:");
System.out.println("-1. complete and calculate");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
if(i ==-1){
System.out.println("Answer is "+result);
return;
}
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
break;
}
}while(true);
}
I am having a few issues,
I am having issues getting my program to actually end.
I can't figure out when I prompt the user to play again how to initiate a new game.
Any guidance would be appreciated.
Thanks
import java.util.*;
public class HiLowGuessingGame {
public static void main(String[] args) {
// Creates a random number generator
Random random= new Random();
// For getting input from the user
Scanner sc = new Scanner(System.in);
int number = random.nextInt(100);
int guess = +1;
//Counts the number of guesses
int guesscount = 0;
guesscount ++;
//Allows user to quit the game
String input;
int quit = 0;
String playagain;
String y="y";
String n="n";
// Prompts user for their next guess
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
// Loop until the user guesses correctly
while (true){
// Reads the next guess
guess = sc.nextInt();
//If guess it to low or high
if (guess == quit){
System.out.println("Game Over!");}
else if (guess < number ){
System.out.println("Guess is too low, please try again");
guesscount ++; }
else if(guess > number ){
System.out.println("Guess is too high, please try again");
guesscount ++; }
// Correct guess and number of guesses
else {
System.out.println("Your guess is correct = " + number + "\n" +"Number of Guesses = " +guesscount );
while (true) {
// Play again?
boolean isplayagain = true;
while (true) {
System.out.println("play another game?(y/n)");
String playagainResponse = sc.next();
if (playagainResponse.equalsIgnoreCase("y")) {
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
guess = sc.nextInt();
break;
} else if (playagainResponse.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
isplayagain = false;
break;
}
}
if (!isplayagain) {
break;
}
}
}
}
}
}
I ran your code, and I noticed that you use break statements to exit out of the for loops, but you never break out of the outermost for loop, so the game never actually ends.
In this case however, I would recommend not using break and use System.exit(0), which will end the game normally. I'll add a reference link at the bottom. This should fix your issue of the game not ending.
As for your other problem, I'm not sure what you mean. Do you mean that it doesn't restart a new game properly? The random number is only issued at the start of the program, so when a new game is started, the random number stays the same. Also, the guess count isn't reset with a new game. I would just put all the code which resets the variables in the if-statement responsible for starting a new game.
Good luck!
https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int)
I changed your program a bit to do what you want.
If i get what you are trying to do i think this is the code for this.
import java.util.*;
public class HiLowGuessingGame {
public static void main(String[] args) {
// Creates a random number generator
Random random= new Random();
// For getting input from the user
Scanner sc = new Scanner(System.in);
int number = random.nextInt(100);
int guess = +1;
//Counts the number of guesses
int guesscount = 0;
guesscount ++;
//Allows user to quit the game
String input;
int quit = 0;
String playagain;
String y="y";
String n="n";
boolean isplayagain = false;
// Prompts user for their next guess
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
// Loop until the user guesses correctly
while (true){
// Reads the next guess
guess = sc.nextInt();
//If guess it to low or high
if (guess == quit){
System.out.println("Game Over!");
break;}
else if (guess < number ){
System.out.println("Guess is too low, please try again");
guesscount ++; }
else if(guess > number ){
System.out.println("Guess is too high, please try again");
guesscount ++; }
// Correct guess and number of guesses
else {
System.out.println("Your guess is correct = " + number + "\n" +"Number of Guesses = " +guesscount );
// while (true) {
// Play again?
while (true) {
System.out.println("play another game?(y/n)");
String playagainResponse = sc.next();
if (playagainResponse.equalsIgnoreCase("y")) {
System.out.println("New game starts now!");
isplayagain=true;
break;
} else if (playagainResponse.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
isplayagain = false;
break;
}
}
if (!isplayagain)break;//cause of the program to not end if user gives n
}
if(isplayagain){
number = random.nextInt(100);
guesscount=0;
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
isplayagain=false;}
}
}
}
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
}