We are meant to to create a program in java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number. If the number is lower than the random number the program should say: lower! and of higher, the program should say: higher! If the user guesses the right number it should say congratulations you guessed the right number in X amount of tries, This is what I have so far, when I execute in cmd it just spams either higher or lower and I need help working it out.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame{
public static void main(String[] args) {
int random, guess, attempts;
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
random = generator.nextInt(100) + 1;
attempts = 1;
System.out.print("I am thinking of a number between 0 and 100, what do you think it is?");
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
}
System.out.print(random + "is the correct answer and it took you" + attempts + "attempts to guess it!");
}
}
You're only reading the input once and then looping on it forever (you read the input outside the loop).
Try reading the input inside the loop and using do-while loop:
guess = 0;
do {
guess = keyboard.nextInt();
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
} else {
System.out.print("Higher!");
attempts +=1;
}
} while (guess != random);
Place the guess = keyboard.nextInt(); into the while loop to ask again and again.
You only take a single guess and stuck yourself in the while loop, it's like if the number randomized by the program is 70, and for example if the user gave his first attempt as 50, the code will enter the while loop as the number is not 70, but it won't come out as you coded while(guess != random) and guess will ever equal random in our case, and it will be always lower for an infinite time because you give him the ability to enter a single attempt and then you enter an endless while loop without giving him the ability to change his attempt through it, So, you must allow him to has his second, third, ..etc attempts inside the while loop itself, like the following:
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
guess = keyboard.nextInt();
}
The random number generate the number once the we will call the method isNumCorrect again using while loop until it returns true and the guess count will increase every time the number pass through isNumCorrect
import java.util.Random;
import java.util.Scanner;
class guessGame {
int guessedNumber;
int userNumber;
int guess_count;
public guessGame() {
Random rand = new Random();
guessedNumber = rand.nextInt(100);
}
void userNum() {
System.out.println("GUESS THE NUMBER");
Scanner sc = new Scanner(System.in);
userNumber = sc.nextInt();
}
boolean isNumCorrect() {
guess_count++;
if (userNumber == guessedNumber) {
System.out.printf("yes you guessed it right in %d guesses", guess_count);
return true;
} else if (userNumber < guessedNumber) {
System.out.println("too low");
} else {
System.out.println("too high");
}
return false;
}
}
public class cwh_42_guess_the_number {
public static void main(String[] args) {
guessGame g = new guessGame();
boolean b = false;
while (!b) {
g.userNum();
b = g.isNumCorrect();
}
}
}
Related
I'm writing a number guessing game in java.
Number guessing game is a numeric version of famous hangman, where computer picks a
number between a prespecified range and user has to guess that number.
Requirements:
User must guess a number between 0-1000 and tells the user the range of guessed
number.
User has max 10 guesses.
Every time user makes a guess, total guesses reduce by one.
Computer keeps track of all the numbers user has guessed so far and shows this
information before next guess.
If the guess is correct, game ends in a win. In case of incorrect guess, computer gives a
hint to the user. If the user guess is greater than the picked number, then client tell the
user that ‘your guess is bigger’ and in case of being smaller appropriate message is
shown.
In case of invalid guess (alphabets, symbols and repeated guesses) one warning is given
and on next warning user loses a guess
The following code is running fine but it always shows the same number after guesses number. I think its not adding the new input in the arrraylist rather the first one everytime.
import java.util.*;
import java.lang.*;
public class NumberGuess {
public static void main(String[] args) {
int tries = 10;
ArrayList<Integer> guessed = new ArrayList();
int warnings = 2;
int i = 0;
Random rand = new Random();
int random = rand.nextInt(1000);
private void StartMenu () {
System.out.println("\" Welcome to the Number guessing game!\n I am thinking of a number between 0-1000\n You have 1 warning.\n You have 1 warning.\n ------------ ");
}
public char[] ToCharacterArray (String input){
char arr[] = new char[input.length()];
arr = input.toCharArray();
return arr;
}
public boolean CheckInput ( char arr[]){
if (Character.isDigit(arr[0])) {
return true;
} else {
return false;
}
}
String input;
while (tries > 0 && warnings > 0) {
System.out.println("You have " + tries + " guesses left.");
if (tries == 10) {
System.out.println("guessed number: ");
} else {
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(guessed.get(i));
}
}
System.out.println("Please guess a number:");
Scanner sc = new Scanner(System.in);
input = sc.next();
char InputString[] = ToCharacterArray(input);
if (CheckInput(InputString)) {
int intInput = Integer.parseInt(input);
guessed.add(intInput);
if (intInput > random) {
System.out.println("Your guess is greater");
}
if (intInput < random) {
System.out.println("Your guess is smaller");
}
if (intInput == random) {
System.out.println("Congrats! You win.");
System.out.println("The guessed number is: " + intInput);
tries = -1;
}
}
tries--;
}
}
}
The problem is because you iterate over the guessed numbers, and then print out the item of index i from that list. The number i at that point will always be zero, so it will always print just the first element from that list. Instead, you can just print the a, that is the element itself, after the iteration on guessed. Here is how it will look like:
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(a);
}
I am very new to coding and learning JAVA. I was able to execute the below code but I am not sure how to loop this until the user matches the randomNumber. Could you please help.
My current code:
package com.arwa.basicExcercisePart1;
import java.util.Scanner;
public class RandomCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer randomNumber = (int) Math.floor(Math.random() * 6);
System.out.println("Enter a number from 1 to 5: ");
int number = scan.nextInt();
if (number == randomNumber) {
System.out.println("Wow, The entered number matched with the Random Number.");
} else {
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: .");
}
}
}
You can use a while loop like so:
int number;
while((number = scan.nextInt()) != randomNumber){
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: ");
}
System.out.println("Wow, The entered number matched with the Random Number.");
Put a loop around the code that checks the user's input against the random number.
iota's answer is correct but since Aravind is learning I'd like to suggest another more didactic answer. You can use a flag to signal that the user choose the right answer and then get out of the loop. I did this below:
public class RandomCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer randomNumber = (int) Math.floor(Math.random() * 6);
boolean found = false; // flag is false at beginning
while (!found) { // stay in the loop till answer is correct
System.out.println("Enter a number from 1 to 5: ");
int number = scan.nextInt();
if (number == randomNumber) {
found = true; /// will finish the loop
System.out.println("Wow, The entered number matched with the Random Number.");
} else {
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: .");
}
}
}
}
package w3school;
import java.util.Random;
import java.util.Scanner;
public class nyttprogram {
static void indata() {
{
Scanner determinedNumber = new Scanner(System.in);
int user, computer, number, user2;
System.out.println("Input a number from 0-10");
user = determinedNumber.nextInt();
Random random = new Random();
int randomInt = random.nextInt(10);
if (user == randomInt) {
System.out.println("You guessed the correct number!");
} else {
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + randomInt);
}
System.out.println("Input 1 if you want to try again: ");
}
}
public static void main(String[] args) {
indata();
}
}
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
The "start over" logic based on some conditions is usually implemented with while and do/while loops.
First let's extract those conditions. We want to iterate again (start over) if:
The user's guess is wrong.
The user's guess is correct, but they input a number different than 1 when asked if they want to continue.
Since we want to run the program at least once, the natural approach would be with a do/while. This will run one iteration, then check against the conditions wanted.
Here's what it looks like:
private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the correct number!");
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
} else {
// Wrong answer, loop again
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
isLoopContinue = true;
}
} while (isLoopContinue);
}
I'm practicing Java and i tried to make a guess game but i want the game to ask for input again when the user don't guess the number right. When i guess the number wrong the loop just continuous to guess numbers until the number is the right one and the game ends.
import java.util.*;
class GuessGame {
private Scanner userInput = new Scanner(System.in);
public GuessGame(){
System.out.println("~~~Guess Game~~~");
System.out.println("~~~Guess a number between 0 and 9~~~");
}
int guessedNumber = 0;
public void gameStart(){
System.out.println("Guess a number: ");
boolean guessedRight = false;
boolean gameOn = true;
int userNumber = userInput.nextInt();
while(gameOn){
guessedNumber = userNumber;
int randomNumber = (int) (Math.random() * 10);
if(randomNumber == guessedNumber){
guessedRight = true;
}
if(guessedRight){
System.out.println("You guessed " + guessedNumber);
System.out.println("The number is " + randomNumber);
System.out.println("You won!!!");
System.out.println("Game Over!!!");
break;
}else{
System.out.println("You guessed " + guessedNumber);
System.out.println("The number is " + randomNumber);
System.out.println("Try again!!!");
}
}
}
}
The int userNumber = userInput.nextInt(); line is responsible for getting the number that the user entered from the input line. Moving this line inside the while loop will ask for a number each time the loop is ran (which is only once if the user guesses right the first time).
Just call the method from a loop:
public GuessGame(){
while(true) {
System.out.println("~~~Guess Game~~~");
System.out.println("~~~Guess a number between 0 and 9~~~");
gameStart();
}
}
This will simply restart the game as soon as the gameStart() method exists. (Which is when the user has guessed the right number)
As part of our coursework myself and another person in my class have to make a Guessing Game where a random number is generated between 1 to 100 and the user has a maximum of 6 guesses to try and guess the number. I also have to create a "session" where the user can enter their name and it will store their results into a text file. I have got it working to a point where they can play the game and successfully input their name, but if you select the option that you want to play again, it says 'Process completed' and exits the program. Help would be greatly appreciated, here is what I have so far;
Code:
import java.util.Random; //importing the Random class
import java.util.Scanner; //importing the Scanner class
/* Author Laura Brown 28/02/2014 */
public class TheGuessingGame
{
public static void main(String[] args)
{
Random generator = new Random(); //creates a random number between 1-100
int TARGET = generator.nextInt(100) + 1; //establishes the target number
int guess;
int count = 0;
String userName;
String another = "y";
Boolean flag = false;
Boolean anotherFlag = true;
Scanner consoleIn = new Scanner(System.in); //creating a new Scanner object
Scanner name = new Scanner(System.in); //creating a new Scanner object
System.out.print("Hello! Please enter your name:\n"); //asking for user input
userName = name.nextLine();
System.out.print("Hello "+ userName+ ", and welcome to the game!\n");
System.out.print("Can you guess what it is?\n");
do { //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else {
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
}
}
You need to add another loop. Stylistically speaking, I would avoid using do...while loops, as they are difficult to read. I have included a while loop done the more traditional way to show you how blissfully sexy they are.
while(anotherFlag)
{
TARGET = generator.nextInt(100) + 1; //establishes the target number
System.out.print("Can you guess what it is?\n");
do
{ //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else
{
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
}
The above won't work fully, you need to set anotherFlag to false if the user inputs 'no'. That should be a relatively simple exercise, but the above will get the program to loop over and over.
public static void main(String[] args)
{
Random generator = new Random(); //creates a random number between 1-100
int guess;
int count = 0;
int Target;
String userName;
String another = "y";
Boolean flag = false;
Boolean anotherFlag = true;
Scanner consoleIn = new Scanner(System.in); //creating a new Scanner object
Scanner name = new Scanner(System.in); //creating a new Scanner object
System.out.print("Hello! Please enter your name:\n"); //asking for user input
userName = name.nextLine();
System.out.print("Hello "+ userName+ ", and welcome to the game!\n");
while (another.equalsIgnoreCase("y")) // this will check if your user input "another"
{
TARGET = generator.nextInt(100) + 1; //establishes the target number
System.out.print("Can you guess what it is?\n");
do { //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else {
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
consoleIn.nextLine();
}
}
}
Added in another loop to loop the whole gaming process. And brought down the random generating method to be inside the loop to regenerate a new number. Try it. Anyway I added another line consoleIn.nextLine(); after your user input to clear the carriage return buffer for .next() method.