Very simple game about Guessing The Number - java

/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!!!");
}
}

Related

How to combine two programs in one class

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.

redirect a loop within a loop for only "else"

I'm a total beginner and am working on a practice assignment. I need to be able to re-print the same addition problem if the user has answered incorrectly, but I'm not sure how to do that. All my attempts have lead to a new random addition problem appearing or adding another new random to the original, which is also not desired. I'm sure it's simple, but I am lost. Thanks in advance for any tips!
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do {
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b)) {
System.out.println("CORRECT!");
} else if (ans==0) {
System.out.println("Good bye!");
} else if (ans!=(a+b)) {
System.out.println("Incorrect, try again.");
}
} while (ans!=0);
}
}
Just simplify your code a little bit, don't overthink. You generate answers every time you get into the loop, generate your numbers outside so they stay consistent, also, a do-while, isn't necessary, just break your loop if the answer is correct or they placed 0. Also, you need to make sure that the user entered a number, so a try-catch should be placed while getting the input.
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
int ans;
while (true) {
System.out.printf("%d + %d = ?%n", a, b);
try {
ans = Integer.parseInt(input.next());
} catch (NumberFormatException e) {
System.out.println("Please enter a number!");
continue;
}
if (ans == 0) {
System.out.println("Goodbye!");
break;
} else if (ans == a + b) {
System.out.println("Correct!");
break;
} else {
System.out.println("Incorrect!");
}
}
Please see modification inline:
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
// here you keep asking the user over and over
//until they give the right result
do{
System.out.println("Incorrect, try again.");
//show again the equation to the user
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
}while(ans!=(a+b));
}
}
while (ans!=0);
}
}
Use this simple source code and similar to you (minor change):
try (Scanner input = new Scanner(System.in)) {
Random rand = new Random();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans, a, b;
ans = a = b = 0;
do {
a = rand.nextInt(10) + 1;
b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b + " = ");
try{
//Getting input as String and casting to Integer
ans = Integer.parseInt(input.nextLine());
if (ans == 0) {
System.out.println("Good bye!");
} else if (ans == (a + b)) {
System.out.println("CORRECT!");
} else if (ans != (a + b)) {
System.out.println("Incorrect, try again.");
}
}catch (NumberFormatException nfe){
System.out.println(nfe);
}
} while (ans != 0);
}
class generateNum{
Random rand = new Random ();
int a=rand.nextInt(10)+1;
int b=rand.nextInt(10)+1;
public void generate(){
System.out.print(a + " + " + b +" = ");
}
public int getsum(){
return a+b;
}
}
public class Test02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
generateNum gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
int com=gnum.getsum();
do
{
if (ans==com)
{
System.out.println("CORRECT!");
gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
com=gnum.getsum();
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=com)
{
System.out.println("Incorrect, try again.");
gnum.generate();
ans = input.nextInt();
}
}
while (ans!=0);
}
}
There are few changes in your condition. Update your else-if(ans!=(a+b)) block.
import java.util.Random;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
boolean flag = false;
do{
System.out.println("Incorrect, try again.(0 for skip)");
int againAns = input.nextInt();
if(againAns == (a+b)){
System.out.println("CORRECT!");
flag = true;
}else if(againAns == 0){
System.out.println("You skip the answer..");
flag = true;
}
}while(flag != true);
}
}while (ans!=0);
}
}

Why is my string input being skipped?

I've been getting frustrated because my input is being skipped by the program for some reason. This causes the while loop to be skipped and the program to stop.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.println("Guess a number between 1 and 10.");
int count = 1;
int guess = input.nextInt();
int answer = random.nextInt(1) + 1;
while(guess != answer)
{
System.out.println("Wrong answer. Try again.");
guess = input.nextInt();
count++;
}
System.out.println("\nIt took " + count + " guesses to guess " + answer + ".");
System.out.println("\nWould you like to play again (Y/N)?");
String decision = input.nextLine(); // The program skips this input
decision = decision.toUpperCase();
while(decision.equals("Y"))
{
System.out.println("Guess a number between 1 and 10.");
count = 1;
guess = input.nextInt();
answer = random.nextInt(1) + 1;
while(guess != answer)
{
System.out.println("Wrong answer. Try again.");
guess = input.nextInt();
count++;
}
System.out.println("\nIt took " + count + " guesses to guess " + answer + ".");
System.out.println("\nWould you like to play again (Y/N)?");
decision = input.nextLine();
decision = decision.toUpperCase();
}
System.out.println("Thanks for playing.");
}

Having issues with having a program re-run

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');

Creating 1 decimal place

So I am more or less completely done with this code that runs a guessing game. At the end it prints the total results for all games played. This includes total games, total guesses, avg guesses/game and the best score. I have it all worked out except i need the avg guesses/game to show 1 decimal place but the System.out.printf("Guesses/game = %.1f") isn't working and idk why
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
int bestGame = Integer.MAX_VALUE;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) { //repeats until user enters a statement besides y when asked to play again
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
bestGame = Math.min(bestGame, numberOfTries);
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.printf("Guesses/game = ", totalGuesses/totalGames);
System.out.println("Best game = " + bestGame);
}
}
both totalGuesses and totalGames are integers, so when you divide them you get an integer, whereas %f needs a floating point number.
Instead cast one to a floating point number for floating point division:
totalGuesses/(double)totalGames
Try a decimal formatter if for some reason you're simply getting the wrong output:
DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(avgGuesses)); //or whatever your var name is

Categories

Resources