I have created two games and now I am working on menu
It should run each game after user selected each of them
Menu Must look like this:
Hello! Type 'letter' or 'number' to choose game
Heres first game:
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
System.out.println("Guess a number between 1 and 100:");
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
int guess = 0;
while (guess != theNumber)
{
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
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();
}
}
Heres the second
import java.util.Scanner;
public class GuessTheLetter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
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();
}}
Must i use multiple classes, or put everything into 1, how can i combine theese two games in one?
You can put each game into one function and then just call them in the main of that class. You do not need 2 classes for this. You can also add a condition that would decide which function to call.
Related
I am doing a guessing game where in I can input 1-100 but I am having a trouble in only accepting numbers if I typed a letter when I first run the program it will give me error and execute the program instantly image herebut if ityped number after I start the program and type letter next it give me a wrong message it should only display message saying "invalid input".image here Any suggestion thanks.
package m1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class M1{
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int between = 100;
int secretNumber = (int)(Math.random()*between);
int inputNum = 0;
int guesses = 0;
System.out.println("Please enter your guess: ");
inputNum = Scanner.nextInt();
guesses++;
while (inputNum != secretNumber) {
try {
// number too high or too low
if (inputNum > 100 || inputNum < 1) {
System.out.println("Out of Range!");
System.out.println("Enter a guess between 1 and " + between + ".");
inputNum = Scanner.nextInt();
}
// less than secretNumber
if (inputNum < secretNumber) {
System.out.println("Too Low...Try Again!");
inputNum = Scanner.nextInt();
guesses++;
}
// greater than secretNumber
if (inputNum > secretNumber) {
System.out.println("Too High...Try Again!");
inputNum = Scanner.nextInt();
guesses++;
}
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
Scanner.next();
}
}
System.out.println("\nWell done! The secret number was " + secretNumber + "." + "\nYou took " + guesses + " guesses.");
}
}
Generally, name variable names in java using camelCase in most cases.
You don't actually need to catch any exception in your case as you can simply do scanner.next() if scanner.hasNextInt() is false. Prompting the user to enter specifically a number this time.
Try the below code:
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
class Main {
private static final String GUESS_PROMPT_PATTERN = "Please enter a guess between %d and %d inclusive: ";
private static final String WIN_PROMPT_PATTERN = "Well done! The secret number was %d. You took %d guesses.\n";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimumGuess = 1, maximumGuess = 100;
int secretNumber = ThreadLocalRandom.current().nextInt(minimumGuess, maximumGuess + 1);
int guesses = 0;
String guessPrompt = String.format(GUESS_PROMPT_PATTERN, minimumGuess, maximumGuess);
System.out.println("Lec's Guessing Game");
System.out.println("====================");
System.out.print(guessPrompt);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
guesses++;
int inputNum = scanner.nextInt();
if (inputNum == secretNumber) {
break;
}
// Input number too high or too low.
if (inputNum > maximumGuess || inputNum < minimumGuess) {
System.out.println("Out of Range!");
scanner.nextLine();
System.out.print(guessPrompt);
}
// Input number was less than the secret number.
else if (inputNum < secretNumber) {
System.out.println("Too Low... Try Again!");
System.out.print(guessPrompt);
}
// Input number was greater than the secret number.
else {
System.out.println("Too High... Try Again!");
System.out.print(guessPrompt);
}
} else {
System.out.print("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
System.out.printf(WIN_PROMPT_PATTERN, secretNumber, guesses);
}
}
I am writing a program that will ask the user to guess a random number 6 times. The program has to ask if they want to play again and will keep a running total of the wins/losses.
How would I have the program rerun?
heres the code:
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to Higher/Lower!");
System.out.println("Enter your name: ");
input = keyboard.nextLine();
while(input.equalsIgnoreCase("yes")); {
number = randomNumbers.nextInt(100) + 1;
System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }
for(int num = 1; number != guess && number <= 6; num++) {
System.out.println("Enter guess " + num + ":");
guess = keyboard.nextDouble();
if(guess < number)
System.out.println("higher.");
else if(guess > number)
System.out.println("lower.");
else
System.out.println("Congratulations!"); }
if(guess == number) {
System.out.println("You guesses my number!"); wins++; }
if(guess != number) {
System.out.println("Sorry, " + input + " my number was " + number +
"You lose!"); losses++; }
System.out.println("Do you want to play again? (Yes/No): ");
repeat = keyboard.nextLine();
if(input.equalsIgnoreCase("no")); {
System.out.println("Thanks for playing!"); }
System.out.println(wins + " wins");
System.out.println(losses + " losses");
}
}
It is skipping over asking me if i want to play again or not and i dont know what kind of loop to use
Wihtout your code, I'm assuming this is what you need.
boolean doContinue = true;
do {
//guess random number 6 times
//do you want to continue?
// yes -> doContinue = true;
// no -> doContinue = false;
} while (doContinue );
I would suggest making your loop a do-while loop like this:
do {
for (int i=0; i<6; i++){
/*
insert code for the guessing/checking/etc.
*/
}
System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');
This program is a guessing game in which you input a letter between a and j and try to guess the randomly chosen answer. It works correctly, but I want to use a for loop to encompass all three guesses instead of writing them all out separately. Any suggestions on how to start this?
import java.util.Scanner;
import java.lang.Math;
import java.util.Random;
class Guess{
public static void main( String[] args ){
Scanner sc = new Scanner(System.in);
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
for(int i = 0; i<3; i++){ //this is where I'm having trouble
System.out.print("Enter your first guess: ");
Random r = new Random();
char i = (char)(r.nextInt(10) + 'a');
char b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
System.out.print("Enter your second guess: ");
b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
System.out.print("Enter your third guess: ");
b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
}
if(b!=i){
System.out.println("You lose. The letter was " +i+ ".");
}
}
}
Store the character the user should guess in a variable outside the loop.
Then inside the loop ask them to attempt guess number i+1 where i is the loop counter (or you can change to using a 1 based index).
If execution continues after the loop then it means they lost.
Here is an example:
import java.util.Random;
import java.util.Scanner;
class Guess {
public static void main(String[] args) {
int maxGuesses = 3;
System.out.println("I'm thinking of a letter in the range a to j. You have " + maxGuesses + " guesses. ");
Random r = new Random();
char i = (char) (r.nextInt(10) + 'a');
Scanner sc = new Scanner(System.in);
String[] guessDescription = { "First", "Second", "Third" };
for (int g = 0; g < maxGuesses; g++) {
// use predefined guess description for 1-3, otherwise a generic description that works for any number of guesses above 3
if (g < guessDescription.length) {
System.out.print("Enter your " + guessDescription[g] + " guess:");
} else {
System.out.print("Enter guess #" + (g + 1) + ":");
}
char b = sc.next().charAt(0);
if (b > i) {
System.out.println("Your guess is too high. ");
} else if (b < i) {
System.out.println("Your guess is too low. ");
} else if (b == i) {
System.out.println("You win! ");
return;
}
}
System.out.println("You lose. The letter was " + i + ".");
}
}
you can use a nested loop.
this part is basically the same, and can be in inner loop (of 3 iterations)
System.out.print("Enter your ... guess: ")
char b = sc.next().charAt(0);
if(b>i){
System.out.println("Your guess is too high. ");
} else if(b<i){
System.out.println("Your guess is too low. ");
} else if(b==i){
System.out.println("You win! ");
return;
}
but the System.out.print("Enter your ... guess: ") is different every iteration. You can create const array of string with the strings {"first", "second", "third"} and access the correct string by the index of the loop (use format string here...)
Map your letters into a List<> or ArrayList<> then use for-each loop
Check this answer for a simple example of how to use for-each loop:
You just need to replace your line Enter your .... guess.
Based on i, you should keep a mapping like
{ 0:First,1:Second,2:Third}
Scanner sc = new Scanner(System.in);
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
List < String > strList = new ArrayList <String> ( );
strList.add("FIRST");
strList.add("SECOND");
strList.add("THIRD");
Random r = new Random();
char randX = (char)(r.nextInt(10) + 'a');
for(int i = 0; i<3; i++){ //this is where I'm having trouble
System.out.print("Enter your"+ strList.get(i)+ " guess: ");
char b = sc.next().charAt(0);
if(b==i){
System.out.println("You win! ");
return;
}
else
{
if(b>randX)
{
System.out.println("Your guess is too high. ");
}
else
System.out.println("Your guess is too low. ");
if ( b !=randX && i==2 )
{
System.out.println("You lose. The letter was " + randX + ".");
}
}
}
Here is a quick example with a loop to play again if the game is over
class Guess {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random r = new Random();
char toGuess;
char yourGuess;
boolean playing = true;
boolean lost = true;
while(playing) {
toGuess = (char) (r.nextInt(10) + 'a');
System.out.println("NEW GAME");
System.out.println("========");
System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");
for (int j = 0; j < 3; j++) {
switch (j) {
case 0:
System.out.print("Enter your first guess: ");
break;
case 1:
System.out.print("Enter your second guess: ");
break;
case 2:
System.out.print("Enter your third guess: ");
break;
default:
System.out.println("Something went wrong. Game is closing!");
System.exit(0);
break;
}
yourGuess = sc.next().charAt(0);
if (yourGuess > toGuess) {
System.out.println("Your guess is too high.");
} else if (yourGuess < toGuess) {
System.out.println("Your guess is too low. ");
} else if (yourGuess == toGuess) {
System.out.println("You win! ");
lost = false;
break;
}
}
if(lost==false){
System.out.println("Sorry, you lost!");
}
System.out.print("Do you want to play again? (y=yes | n=no): ");
if(!sc.next().equals("y")){
playing=false;
}
}
}
}
Im making a guessing game for my class and I need some help for adding a "play again" feature at the end of the game when you've guessed the right number:
public class GuessingGame
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numtoguesses = rand.nextInt(1000) + 1;
int counter = 0;
int guess = -1;
while (guess != numtoguesses)
{
System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
guess = input.nextInt();
counter = counter + 1;
if (guess == numtoguesses)
System.out.println ("YOU WIN MOFO!");
else if (guess < numtoguesses)
System.out.println ("You're to cold!");
else if (guess > numtoguesses)
System.out.println ("You're to hot!");
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
}
}
One simple approach would be to move the code you've written into a function
public void play() {
...
}
and from main do something like:
do {
play();
playAgain = promptUser;
} while(playAgain);
Just put another while loop over everything.
boolean playing = true;
while(playing) {
while(guess != numtoguesses) { // All code }
System.out.println("Do you wish to play again? Y/N");
String answer = input.nextLine();
playing = answer.equalsIgnoreCase("y");
count = 0;
guess = -1;
}
Everything together:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numtoguesses = rand.nextInt(1000) + 1;
int counter = 0;
int guess = -1;
boolean playing = true;
while(playing) {
while (guess != numtoguesses) {
System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
guess = input.nextInt();
counter = counter + 1;
if (guess == numtoguesses)
System.out.println ("YOU WIN MOFO!");
else if (guess < numtoguesses)
System.out.println ("You're to cold!");
else if (guess > numtoguesses)
System.out.println ("You're to hot!");
}
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
System.out.println("Do you wish to play again? Y/N");
String answer = input.nextLine();
playing = answer.equalsIgnoreCase("y");
count = 0;
guess = -1;
numtoguesses = rand.nextInt(1000) + 1;
}
You should extract this in a few methods, but I'll leave that up to you.
There are a lot of options I can think about. The quickest:
-- place all the code between lines int numtoguesses = rand.nextInt(1000) + 1; (inclusive) and end of main method inside an infinite loop
-- at the end of your current code block, add an interogation to the user, asking him whether he/she wants to play again (you can define a convention for the pressed keys); this part is placed also inside the infinite loop
-- if he/she doesn't want to, break the (outer) infinite loop
/hello, I am trying to learn how to use "break" commend in java as well as continuing loop with "y or n" choice. I am writing this game Guessing Number and I have some trouble with "y" choice. I will try to explain, to write a game of guessing number was easy so I started to add some conditions like the possibility on the and to play again or not, later I was thinking that would be more interesting if I add possibility to quit any time player wish, but that does not working correctly. Please help, thats my code
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}
Here is an alternative that achieves that same outcome
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess = 0;
int number_of_tries = 0;
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
guess = input.nextInt(); //get first input
while (guess != -1)
{
int number_guess = rand.nextInt(5) + 1;
++number_of_tries;
//check if user wins and exits loop
if (isWin (number_guess,guess))
{
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? [1 yes/ -1 no]: ");
guess = input.nextInt();
if (guess == -1)
break;
else
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
}
else if (number_guess < guess )
{
System.out.println(" Guess is too High " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
else if (number_guess > guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
}
System.out.println ("bye bye");
}
public static boolean isWin (int number,int guess)
{
return (number == guess) ? true :false;
}
}
You forgot to wait for user input after this statement:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
E.g. you could try next approach:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (input.hasNext()) {
if (another.equalsIgnoreCase("y")) {
play_again = true;
input.next();
} else {
play_again = false;
}
}
It looks like your braces are messed up for your play again if statement
This will work.
package aa;
import java.util.Random;
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
break;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
input.next();
if (win == true){
System.out.println(" You Win!!! ");
}
else{
System.out.println(" Good Luck Next Time!!! ");
System.out.println(" The number was " + number_guess);
}
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
another = input.next();
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
System.out.println("Thank you!!!");
}
}