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);
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.
This is a Hi-Lo number guessing game code, and the program ends either when the user gets the correct number or enters -1 while playing the game.
Here, I was wondering if it is possible to make the program run again even after the user enters -1 and the game ends, for example, in a situation where the user feels like restarting the game without finishing the first game.
import java.util.Random;
import java.util.Scanner;
public class HighLowGame {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
int guess = scanner.nextInt();
**//if user enters -1, the game ends
if(guess == -1){
break;
}**
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
count = 0;
System.out.println("Would you like to play the game again?(yes/no): ");
String another = scanner.next();
if (another.equalsIgnoreCase("no")) {
break;
}
// if the user wants to play the game one more time, it starts again
else {
number = generator.nextInt(100) + 1;
System.out.println("Please guess the number(Enter -1 to quit): ");
}
}
}
}
}
You can just put the game into a method, and when the method ends, you just ask them.
Main:
public static void main(String[] args){
boolean flag = true;
while(flag){
play();//play the game
Scanner input = new Scanner(System.in);//read the respound
System.out.println("want to play again?");
if(input.nextLine().equal("no"){//Want to play? BTW: I'm assuming you only enter "no" or "yes"
flag = false;//Don't want to play
}
}
}
And the method:
public static void play(){
//create scanner, variables and a random number
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
//prompt user to enter a number
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
//user enters a number
int guess = scanner.nextInt();
//if user enters -1, the game ends
if(guess == -1){
break;
}
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
//displays the message and the attempt count
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
}
}
}
BTW: you said when the user enters -1, you end the game, then why in the world do you want to ask the user again ?_?
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!
I want the user to try and guess the letter and not the number, but i cannot workout how to do this!
(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
Any help would be greatly appreciated! And i can display my code if it is needed
public class Stack {
public static void main(String[] args) {
Random rand = new Random(); //This is were the computer selects the Target
int guess;
int numGuesses = 0;
int Target;
String userName;
String playagain;
boolean play = true;
int session = 0;
int sessions = 0;
int bestScore = 0;
Scanner consoleIn = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
userName = name.nextLine();
System.out.println("Hello " + userName + " :) Welcome to the game!\n");
while (play = true) {
session++;
Target = rand.nextInt(26) + 1;
System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have
do {
guess = consoleIn.nextInt();
numGuesses++;
if (guess > 26)
System.out.println("Error! Above MAXIMUM range");
else if (guess <= 0)
System.out.println("Error! Below MINIMUM range");
else if (guess > Target)
System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
else if (guess < Target)
System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
} while (guess != Target && numGuesses < 5);
if (guess == Target) {
System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
sessions++;
} else {
System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!"); //This tells the player that they failed to find the number and then tells them what the correct answer
}
{
Scanner answer = new Scanner(System.in);
System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
playagain = answer.nextLine();
if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
play = true;
numGuesses = 0;
} else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
play = false;
System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
System.out.println("You had " + session + " Goes");
System.out.println("The number of times you guessed correctly: " + sessions + "");
break;
}
}
}
}
}
use arrays of characters
char[] chars = ['A','B','C'...];
and use the random numbers to map to each character
char targetLetter = chars[r.nextInt(26)];
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Guess the Letter");
String myLetter=scan.nextLine();
//get the letter of myLetter variable then convert to Uppercase
char enteredLetter=Character.toUpperCase(myLetter.charAt(0));
//26 only because the characters array starts with index 0
char[] characters ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//I had created a parrallel array symbolizing int value of each letter
int[] range={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
//this variable convert user input to one of the array element of range
int userInputToInt=0;
//this variable is for knowing what int[] range array element must the value of userInputToInt fall
int userInputControlLoop=0;
char randomLetter=characters[(int)(Math.random()*26)];
// get the random input of computer convert it to int
int computerInputToInt=0;
//this loop is for getting the int value of randomLetter input by the computer
for(int i=0;i<characters.length;++i)
{
if(randomLetter==characters[i])
{
computerInputToInt=range[i];
}
}
//this loop is for getting the int value of user inputted letter
for(char i:characters)
{
if(enteredLetter==i)
{
userInputToInt=range[userInputControlLoop];
}
++userInputControlLoop;
}
//test the entered letter of user
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if greater than computer input
else if(userInputToInt>computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too high");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if lesser than computer input
else if(userInputToInt<computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too low");
System.out.println("The letter is:"+randomLetter);
}
}
Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding A-Z:
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
...
int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) {
System.out.println("Correct!");
} else {
System.out.println("Guess again!")
}
You can implement it in this approach :
1- Create a String alphabet with the characters that you want.
2- declare the size of alphabet as n variable which will control the random generator range.
3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.
program code will be :
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int n = alphabet.length();
Random r = new Random();
System.out.println(alphabet.charAt(r.nextInt(n)));
hope will help solve your problem.
public class Picnic1 {
// RULE 0: This code is provided as a working example.
// This rule tests for whether a word starts with the letter 'b' (allowed to the picnic).
public static boolean rule0(char[] array) {
if (array[0] == 'b') {
return true;
}
else {
return false;
}
// itemMessage:
// Return message about whether a particular item is allowed to the picnic.
public static String item ( double[] a){
// This code works, providing output like these examples:
// "banana: true"
// "collie: false"
// It needs to be replaced with a more suitable output.
// Instead it should return, for example:
// "Yes, you can bring a banana to the picnic."
// "No, you cannot bring a collie to the picnic."
if (a[0] == 'b') {
System.out.println("Yes, you can bring a" + 'a' + "to the picnic");
}
else if (a[0] != 'b') {
System.out.print("No, you can not bring a " + 'a' + "to the picnic");
}
}
}
}
Im fairly new to java and im having trouble getting this to loop? The code works fine, its just that after the user guesses correctly the code stops.
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Chapter3HighLow {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random(); //gives random numbers each time
int correctNum = random.nextInt(100);
int NumberOfTries = 0; // tells how many guesses it took
while (true) {
System.out.println("Hi! Please enter a number between 1-100! (if you would like to quit, please press -1)");
int guess1 = input.nextInt();
NumberOfTries++; //user enters their guesses
if (guess1 == (-1)) {
break; //breaks the loop if the user enters -1
}
if(guess1 < correctNum){
System.out.println("The number inserted is too low!");
}
else if(guess1 > correctNum){
System.out.println("The number inserted is too high!");
}
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took
}
}
}
}
I'm not entirely sure what you're asking, however, from what I can understand, you are looking to get your game to loop continuously until the user wants to stop playing. So what you are looking for is a method which gives the user a choice whether they want to play again. My suggesting is using boolean. The following code demonstrates this for your example:
import java.util.Random;
import java.util.Scanner;
public class Chapter3HighLow {
private static boolean playAgain(){
Scanner sc = new Scanner(System.in);
String usrInput = "";
System.out.println("Play again? (Y/N)");
usrInput = sc.next();
if(usrInput.equalsIgnoreCase("Y")){
return true;
}
else if(usrInput.equalsIgnoreCase("N")){
return false;
}
else{
return false;
}
}
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random(); //gives random numbers each time
int correctNum = random.nextInt(100);
int NumberOfTries = 0; // tells how many guesses it took
int guess1 = 0;
do{
do{
System.out.println("Please guess a number between 1-100!");
guess1 = input.nextInt();
NumberOfTries++; //user enters their guesses
if (guess1 == (-1)) {
break; //breaks the loop if the user enters -1
}
if(guess1 < correctNum){
System.out.println("The number inserted is too low!");
}
else if(guess1 > correctNum){
System.out.println("The number inserted is too high!");
}
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took
}
}while(guess1 != correctNum);
correctNum = random.nextInt(100);
NumberOfTries = 0;
}while(playAgain() == true);
}
}
Read more about methods here.
Read more about the boolean data type here.
Your final else appears to be missing a break. Like
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries");
break; // <-- add this.
}
or you might make that the while condition. Something like,
int guess1 = -1;
while (guess1 != correctNum) {
System.out.println("Hi! Please enter a number between 1-100! "
+ "(if you would like to quit, please press -1)");
guess1 = input.nextInt();
if (guess1 == (-1)) {
break;
}
NumberOfTries++;
if (guess1 < correctNum) {
System.out.println("The number inserted is too low!");
} else if (guess1 > correctNum) {
System.out.println("The number inserted is too high!");
} else if (guess1 == correctNum) {
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries");
}
}
Does it really stop after guessing it right ?