How to let the user attempt many times? - java

import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}

public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}

All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.

Related

One expected line of output is not printed

import java.util.Random;
import java.util.Scanner;
public class Activity3 {
public static void main(String[] args) {
//Variables
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10);
do {
System.out.println("Guess the random generated number of the machine from 1-10");
int guess = input.nextInt();
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
} else if (guess <= 0 && guess >= 11) {
System.out.println("Invalid Number!");
}
if (guess > 1 && guess < 10){
System.out.println("You Lose:<");
}
System.out.println("Do you want to try again?");
} while (input.next().equalsIgnoreCase("YES"));
input.close();
}
}
If I guess the correct number it outputs " you win!".
If I guess wrong it outputs "you lose". But If I guess a number that isn't in 1-10 it doesn't output the "Invalid Number" and just proceeds to output the "Do you want to try again?".
Random#nextInt(int) will return a value from 0 to bound - 1, so it's possible that the guess could be 0 in your code. You'd correct this by adding 1 to the guess, for example int num = Machine.nextInt(10) + 1;
Look at your logic...
else if(guess <= 0 && guess >= 11) {
if guess <= 0 AND guess >= 11 ... well, that's impossible.
I would change your logic flow, focusing on "happy paths" first.
That is, is the input within the acceptable range? If so, is guess == num if so, you win, otherwise print error messages.
For example...
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10) + 1;
boolean done = false;
do {
System.out.println("Guess the random generated number of the machine from 1-10");
// Read the WHOLE line of text, removing the new line from the
// buffer which would otherwise be left by Scanner#nextInt
// and would cause no end of issues
String text = input.nextLine();
try {
// Try and parse the text to an int
int guess = Integer.parseInt(text);
if (guess >= 1 && guess <= 10) {
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
num = Machine.nextInt(10) + 1;
System.out.println("Would you like to play another game? (Yes/No)");
} else {
System.out.println("Incorrect, guess again");
System.out.println("Do you want to try again? (Yes/No)");
}
// Prompt the user to try again or play another game
text = input.nextLine();
done = !"yes".equals(text.toLowerCase());
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException exp) {
System.out.println("Not a valid number");
}
} while (!done);

Looping this guessing game continuously

I'm fairly new to java and I was wondering how could I reset this game to ask another number after the user guessed it correctly?
Here's my code so far:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
if(guess == -1){
System.out.print("Thank you for playing the game!");
break;
}
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
Just wrap your entire code (except for the scanner initialization) in a while loop that is always true. That way, when one game ends, it will start a new one. Then, instead of breaking your game's while loop when the user enters a -1, just use System.exit(0), which will end your program with a status code of 0, indicating that the program executed successfully.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
while (true) {
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100) {
if (guess == -1) {
System.out.print("Thank you for playing the game!");
System.exit(0);
}
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
} else if (guess < a) {
System.out.print("The number is higher. Try again: ");
} else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
Wrap your code in a while (true) this will keep on running your code for ever and ever. Make sure you are also updating your random a after every game and your count. Then from there just check if guess is ever -1 and return when it is. When you call return it will end the method which ends your game.
Scanner keyboard = new Scanner(System.in);
while (true){
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess==-1){
System.out.print("Thank you for playing the game!");
return;
}else if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
You need to:
move your end game condition in the while condition like this while(guess != -1)
move the welcome greetings inside the loop
move the thank you greeting after the game loop is done
reset count and a when the user won a game in order to start fresh
reset guess on every iteration
Now even if the player guesses the number, the loop does not end and the game loop can be stopped only intentionally (by entering -1 = current break condition):
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
while (guess != -1) {
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
a = 1 + (int) (Math.random() * 99);
System.out.println("Congratulations. You guessed the number in " + count + " tries!");
count = 0;
}
guess = 0;
}
System.out.print("Thank you for playing the game!");
}
The code can be refactored even more, for example extract functionality into functions in order to make the code more readable. This also leads to easier maintanence should the variables change or should more conditions come. For example the code can be refactored like this:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int a = 0;
int count = 0;
int guess = 0;
startNewGame();
System.out.println("Welcome to the Number Guessing Game");
while (guess != -1) {
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in " + count + " tries!");
startNewGame();
}
resetGuess();
}
System.out.print("Thank you for playing the game!");
}
private static int generateNewA() {
return 1 + (int) (Math.random() * 99);
}
private static void startNewGame() {
a = generateNewA();
count = 0;
}
private static void resetGuess() {
guess = 0;
}
}
Another solution is to use two nested loops, but IMO for this case loop in a loop is too much and makes the source unnecessary complex.

if a user inputs a letter instead of a number tell them it's not a number

I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here

How to use the JOption on my guessing game?

import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.*;
public class GuessingGameGUI {
public static void main(String[] args) {
Random rand = new Random();
int value = rand.nextInt(32) + 1;
int guesses = 0, LowGuess = 0, HighGuess = 0; //ADDED LowGuess AND HighGuess
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
while (win == false) {
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
guesses++;
if (guess == value) {
win = true;
} else if (guess < value) {
JOptionPane.showInputDialog("Your guess is lower than random number");
LowGuess++; //COUNTER TO KEEP TRACK OF LOW GUESSES
} else if (guess > value) {
JOptionPane.showInputDialog("Your guess is higher than random number");
HighGuess++; //COUNTER TO KEEP TRACK OF HIGH GUESSES
}
}
JOptionPane.showMessageDialog(null, "You win! You are the worst guesser in history!");
JOptionPane.showMessageDialog(null, "The number was: " + value);
// ADDED FROM HERE (GUESSES)
JOptionPane.showMessageDialog(null, "Number of Guesses:" + guesses);
for (int x = 1; x <= guesses; x++) {
for (int a = 1; a <= guesses; a++) {
if (a == guesses) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // TO HERE FOR AMOUNT OF GUESSES
// I ADDED FROM HERE (LOW)
JOptionPane.showMessageDialog(null, "Smaller Guesses:" + LowGuess);
for (int Low_i = 1; Low_i <= LowGuess; Low_i++) {
for (int Low_e = 1; Low_e <= LowGuess; Low_e++) {
if (Low_e == LowGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // Then TO HERE FOR LOW
// I ADDED FROM HERE (HIGH)
JOptionPane.showMessageDialog(null, "Largest Guesses:" + HighGuess);
for (int High_i = 1; High_i <= HighGuess; High_i++) {
for (int High_e = 1; High_e <= HighGuess; High_e++) {
if (High_e == HighGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} //FINALLY TO HERE FOR HIGH
}
}
// when I run my program the message box pops up when i enter my guessing number, however it seems to stop and nothing else pops up to let me know if i guessed to high or to low.
Take these lines, for example:
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
A prompt displays that asks you to "Guess a number between 1 and 32". So you enter the number, and then execution stops because your Scanner is awaiting your input. You need to completely remove your Scanner so you won't have these frequent interruptions.
The showInputDialog method of JOptionPane returns a String, as shown in the example from the Javadocs:
Show a dialog asking the user to type in a String:
String inputValue = JOptionPane.showInputDialog("Please input a value");
As is, you're throwing away the value returned from the method when you should instead be assigning it to your variables. In order to assign the returned value to your int variable guess, use Integer.parseInt:
guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number between 1 and 32: "));
JOptionPane.showInputDialog returns String than you have to convert that String to int using Parse methods, every time you receive input.
String input = JOptionPane.showInputDialog();
Int number = Integer.parseInt(input);

How to use while loop

Ask the user to guess a number until the guess is equal random number. press 0 to quit and ask the user if they want to play again.
My problem, 0 for quit is, not working. How can I make it work with while loop?
thanks
import java.util.Random;
import java.util.Scanner;
public class Guessing
{
public static void main(String[]args){
String playAgain = "y";
final int MAX =100;
int randomNumber;
int numberofGuess = 0;
int guess ;
boolean flag=false;
Scanner input = new Scanner(System.in);
Random rand = new Random();
Scanner inputYes= new Scanner(System.in);
while(playAgain.equalsIgnoreCase("y"))//do
{
System.out.println("Guess a number between 1 and "+ MAX );
randomNumber = rand.nextInt(MAX) +1;
numberofGuess = 0;
System.out.println( "enter a guess(0 to quit):");
guess= input.nextInt();
numberofGuess++;
if(guess >0)
if (guess == randomNumber)
{
System.out.println("you guessed corect.");
System.out.println("you guessed " +numberofGuess+ " times");
}
else if(guess < randomNumber)
System.out.println("you guess is too low.");
else if(guess > randomNumber)
System.out.println("you guess is too high.");
System.out.println("Do you want to play again? (y/n)");
playAgain = inputYes.nextLine();
}//while(playAgain.equalsIgnoreCase("y"));
}
}
Your loop runs until the expression in parantheses is false:
while (true) {
// this will be executed forever
}
while (false) {
// this will never be executed
}
a = 0;
while (a == 0) {
a = 1;
// this will be executed exactly once, because a is not equal 0 on the second run
}
guess = 1
while (guess != 0) {
// this will executed until the user enters "0"
readln(guess);
}
Please keep in mind that this is pseudo code. It will not compile.

Categories