Hi im currently creating a guessing letter game! So far i have made it so you guess between the numbers 1 and 26 using the java.util.random class. However this random number should be converted into the corresponding number within the alphabet! ie a=1 etc..This is where my problem is i dont know how to convert this randomly generated number into a letter! This needs to be related to the integer as i have to able to tell the user if they are above the letter in the alphabet or to low based on the guess they entered! One more thing is that the users guess will be a letter also! Below is my code! Any help will be greatly appreciated!
{
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;
}
}
}
}
Random random = new Random();
char c = (char) (random.nextInt(26) + 'a');
This maps (0 to 25 ) to ('a' to 'z')
Related
Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.
The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!
import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
Random randy = new Random();
//#declaring variables
int num, count = 0;
final int random = randy.nextInt(100);
String input;
char yn;
//#random number
System.out.println("Num = " + random);
//#title or header
System.out.println("Random Number Guessing Game");
System.out.println("===========================");
//#asking user for input
do
{
System.out.print("Guess the random number " +
"from 1 to 100===> ");
num = keyboard.nextInt();
//#if the number the user entered
//#was less than the random number
if(num < random)
{
//#display this message
System.out.println("Your guess is too low try again...");
System.out.println();
}
//#if the number the user entered
//#was less than the random number
if(num > random)
{
//#display this message
System.out.println("Your guess is too high try again...");
System.out.println();
}
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
}
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y');
}
while (num > 1 || num > 100);
}
}
There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
} // You should put an else here
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y'); // This will keep asking if you want to try again so long as you enter a "y"
// But it won't actually let you try.
// Why? Because if you enter a y" it will loop back to the question.
}
while (num > 1 || num > 100); // This should probably be (random != num)
}
}
Here is a revised version
count++;
if (num == random) {
System.out.println("You guessed the random number in " +
count + " guesses!");
} else {
yn = 'x'; // can be anything other than y or n
while(yn != 'y' && yn != 'n') {
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.toLowerCase().charAt(0);
}
}
}
while (num != random && yn == 'y');
}
}
Hopefully this is enough to move you forward.
Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.
As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).
You could try this:
num = -1; // Initialise the number to enable the loop
while (num <= 1 || num >= 100) {
System.out.print("Guess the random number from 1 to 100===> ");
String ans = keyboard.nextline();
try {
num = Integer.parseInt(); // Convert the string to an integer - if possible
} catch (NumberFormatException e) {
// If the user's input can not be converted to an integer, we will end up here and display an error message.
System.out.println ("Please enter an integer");
}
}
My program should execute these steps:
Generate random no from 0 to 100.
Display random no and ask user enter (h/l/c)? (user have to enter one of them).
If it is correct ask user if they like to play again (y/n)? (user must answer (y/n))
I was able to execute Question no.1. Question no.2, random no display but I am unable to type character (h/l/c). Also, I am not able to ask player if they want to play again or not?
Here is what I have done:
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number;
int guess = 0;
int min = 0;
int max = 100;
int answer= (min+max);
number = (int) (Math.random() *100 +1);
System.out.println("Guess a number between 1 and 100.");
//Ask user to type higher 'h', lower 'l' and correct 'c'.
System.out.println("Is it " + number + " ?" + " (h/l/c): " );
//
guess = 50;
while (guess <= 7)
{
System.out.println( "It is: " + guess + "?" + "(h/l/c) : " );
//Type 'h' if guess is high, 'l' for low and 'c' for correct.
if(answer == 'h')
{
max = guess -1;
min = 0;
guess = ((max = min)/2) + min;
guess++;
} else if (answer == 'l')
{
max = 100;
min = guess + 1;
guess = ((max+min)/2);
guess++;
} else if (answer == 'c');
}
System.out.println("Great! Do you want to play again? (y/n): ");
if(answer == 'y')
{
System.out.println("Guess a number between 1 and 100.");
//else prompt another question with if else
} else{
System.exit(0);
}
}
}
Your program does not accept any user input about if the guess is too low or too high.
You declared "answer" with an equation so it should accept a number.
answer would require a char or String value.
answer = keyboard.nextChar(); //read a char
answer = keyboard.nextLine(); //read a String
Im working on this random-number-guessing game. At the end of the game I want the user to be given the option of playing again (or letting someone else play). I've found a couple of similar threads and questions but none have been able to help me solve this little issue. Im pretty sure I can use my while-loop someway but dont know exactly how..
Very new to Java so understand if this is an easy fix..
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args){
Random rand = new Random();
int correctNumber = rand.nextInt(100);
int numberOfGuesses = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
String username = "";
System.out.println("Hello, it is time to play a guessing game.");
System.out.println("We will generate a random number between 0-99, and you will have to try to guess the number in as few attempts as possible.");
System.out.println("You can also choose to give up by pressing \"q\" on your keyboard. \n\nTo get started, press \"s\" on your keyboard.");
input.nextLine();
System.out.println("\nEnter a username: ");
username = input.nextLine();
System.out.println("\nNew username registered: " + username);
while(win == false){
System.out.println("\nGuess a number between 0-99: ");
guess = input.nextInt();
numberOfGuesses++;
if (guess == correctNumber){
win = true;
}
else if(guess < correctNumber){
System.out.println("Too low. Try again!");
}else if(guess > correctNumber){
System.out.println("Too high. Try again!");
}
}
System.out.println("\nYou guessed the correct number which was " + correctNumber + ". Congrats!");
System.out.println("\n" + username + " your number of guesses were: " + numberOfGuesses);
win = false;
}
// System.out.println("\nTo play again (let someone else try) press \"s\", to quit press \"q\".");
// input.nextLine();
// if (input.next().equalsIgnoreCase("q")){
// System.out.println("\nThanks for playing!");
// }
// }else if(input.nextLine().equalsIgnoreCase("s")){
}
//}
What you're describing is called a "game loop". Basically you'd wrap your entire game in a loop which would repeat based on some condition. In this case the condition is whether or not the user wants to play again.
In Java-ish pseudo-code, the structure would look like this:
boolean keepPlaying = true;
while (keepPlaying) {
boolean hasWon = false;
while (!hasWon) {
// play a round in the game
}
keepPlaying = promptUser("Would you like to play again?");
}
The "pseudo" part of that pseudo-code of course being that last line. Simply ask the user if they'd like to play again, and convert the response to the logical value being used by the game loop.
So the game itself is a loop of "rounds" which repeat until a win or loss has occurred. And the program is a loop of "games" which repeat until the user quits.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args){
Random rand = new Random();
int correctNumber = rand.nextInt(100);
int numberOfGuesses = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
String username = "";
String choice = "No"; //new Variable
System.out.println("Hello, it is time to play a guessing game.");
System.out.println("We will generate a random number between 0-99, and you will have to try to guess the number in as few attempts as possible.");
System.out.println("You can also choose to give up by pressing \"q\" on your keyboard. \n\nTo get started, press \"s\" on your keyboard.");
input.nextLine();
System.out.println("\nEnter a username: ");
username = input.nextLine();
System.out.println("\nNew username registered: " + username);
do{
while(win == false){
System.out.println("\nGuess a number between 0-99: ");
guess = input.nextInt();
numberOfGuesses++;
if (guess == correctNumber){
win = true;
}
else if(guess < correctNumber){
System.out.println("Too low. Try again!");
}else if(guess > correctNumber){
System.out.println("Too high. Try again!");
}
}
System.out.println("\nYou guessed the correct number which was " + correctNumber + ". Congrats!");
System.out.println("\n" + username + " your number of guesses were: " + numberOfGuesses);
win = false;
//added the next two lines
System.out.println("Do you want to play again? Type \'Yes\' to play again or \'No' to quit");
choice = input.next();
}
while(choice.equalsIgnoreCase("Yes"));
}
// System.out.println("\nTo play again (let someone else try) press
\"s\", to quit press \"q\".");
// input.nextLine();
// if (input.next().equalsIgnoreCase("q")){
// System.out.println("\nThanks for playing!");
// }
// }else if(input.nextLine().equalsIgnoreCase("s")){
}
//}
Im making a player 2 guesses player 1's number game. Ive made an int counter thats == 10 and is meant to go down everytime player 2 gets answer wrong. I cant get it to work and i need help on how to make this. Youll see what i mean...
package guessMain;
import java.awt.*;
import java.util.Scanner;
public class GuessCodeSource {
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else if (answer <= 100){
System.out.println("Guess in the space below.");
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
}else if (guess != answer);
for (int counter = 10; counter-=1);
System.out.println("You have " + count + " of guesses left");
}
}
}
To make reduce a number by one, use the decrement operator.
For example,
counter--;
would subtract one from the counter.
If you want to subtract more than one, you can use the "-=" operator in the following manner:
counter -= 2;
So, in your code, in the final else if block, you could change the code to the following to reduce "counter" by 1.
else if (guess != answer) {
counter--;
System.out.println("You have " + count + " of guesses left");
}
But, in your code, you never declare the variable counter. Somewhere, most likely at the top of your code, you want to create this variable. To create an Integer variable you do the following:
int counter = 10;
You asked how to LOOP as well, so here it is. Read the comments to gain understanding of what the code does. If you have more questions, ask below.
public static void main(String[] args) {
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
int guess = 0; // Create these variables up here to access them everywhere in "main"
int counter = 0;
boolean continueTheGame = true; // A boolean variable that holds ONLY either true or false
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
// A while loop will continue as long as a boolean expression is true.
// So, we create a boolean variable somewhere above called "continueTheGame"
// As long as this is true, the code INSIDE of the while loop's brackets will repeat.
// If the user has less than zero guesses left, we can set the variable to false,
// which will make the loop stop!
while (continueTheGame == true) { // The start of the while loop
if (answer >= 100) {
System.out.println("BUSTED! I said a number between 1 - 100!");
} else if (answer <= 100) {
System.out.println("Guess in the space below.");
guess = josh.nextInt();
}
if (guess == answer) {
System.out.println("CORRECT!!!!!");
} else if (guess != answer) {
counter--;
System.out.println("You have " + counter + " of guesses left");
if (counter > 0) { // If they have MORE than zero guesses left, loop again!
continueTheGame = true;
} else { // If they have zero guesses left, make it stop looping
continueTheGame = false;
}
}
}
// Once the loop ends, the code will start again here,
// because the bracket above is the final bracket of the WHILE loop
}
Okay, so here is the full functional main method you are looking for:
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else {
System.out.println("Guess in the space below.");
}
for (int count = 10; count>=0; count--) {
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
System.exit(0);
} else {
System.out.println("You have " + count + " of guesses left");
if (count == 0) {
System.out.println("Sorry, you lost, no more tries..");
System.exit(0);
}
}
}
josh.close();
}
I need to add "You got it right in ... guesses!" but I'm not exactly sure how. Can someone please explain to me how to do this in java?
I would like it to display a println at the end saying how many tries it took for the user to get the number correct.
import java.util.*;
public class prog210c
{
public static void main()
{
Scanner sc = new Scanner(System.in);
Random rn = new Random();
int randomNum = rn.nextInt(90) + 10;
System.out.println("I am thinking of a number between 1 and 100");
while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
if(guess < randomNum)
{
System.out.println("Higher--Try Again");
}
else if(guess > randomNum)
{
System.out.println("Lower--Try Again");
}
else if(guess == randomNum)
{
System.out.println("Correct!");
break;
}
else
{
System.out.println("Enter a number between 1 and 100");
}
}
//System.out.println("You got it right in " + + " guesses");
} //end main
} //end class
Just create some int variable to store your number of attempts in and increment it every time you read in a guess.
int attempts = 0;
System.out.println("I am thinking of a number between 1 and 100");
while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
attempts++;
/**
* The rest of your loop code here.
*/
}
System.out.println("You got it right in " + attempts + " guesses");
The simplest way to do this is declared a counter integer, and in your logic increment it every time the user attempts.
int guessCounter = 0;
while(true) // Also do not use an infinite while loop, have an expression that can be terminated
{
...obtain input
if(guess < randomNum)
{
...
guessCounter++;
}
else if (guess > randomNum){
....
guessCounter++;
}
System.Out.println("The number of attempts " + guessCounter);
}
You could do this by creating a variable to store the number of tries, like an int, and then add one to the int every time the user guesses, by using variable++:
public static void main(){
Scanner sc = new Scanner(System.in);
Random rn = new Random();
int tries = 0;
int randomNum = rn.nextInt(90) + 10;
System.out.println("I am thinking of a number between 1 and 100");
while(true){
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
//Rest of your code here
}
System.out.println("You got it right in " + tries + " guesses");
}
and if you want to go even above and beyond, you could make it so it says You got it right in 1 guess instead of it saying You got it right in 1 guesses, if the user gets the number correct on their first try. We can do this by using the ternary Java operator, which is pretty much a compact if-statement:
String s = (tries == 1 ? "guess" : "guesses");
What this is pretty much doing is: if this is true ? do this : else do this
Now we can change the You got it right in... part of your program to say guess instead of guesses if the user guesses the number on their first try:
String s = (tries == 1 ? "guess" : "guesses");
System.out.println("You got it right in " + tries + "" + s);