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)
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);
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
}
public static int getSumOfInput () {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
boolean checkValidity = userInput.hasNextInt();
if(checkValidity) {
int userNum = userInput.nextInt();
userInput.nextLine();
System.out.println("Number " + userNum + " added to the total sum.");
sumOfNums += userNum;
counter++;
} else {
System.out.println("Invalid input. Please, enter a number.");
}
}
userInput.close();
return sumOfNums;
}
}
Hello everybody!
I just started java and I learned about control flow and now I moved on to user input, so I don't know much. The problem is this code. Works just fine if you enter valid input as I tested, nothing to get worried about. The problem is that I want to check for wrong input from user, for example when they enter a string like "asdew". I want to display the error from else statement and to move on back to asking the user for another input, but after such an input the program will enter in an infinite loop displaying "Enter the number X: Invalid input. Please, enter a number.".
Can you tell me what's wrong? Please, mind the fact that I have few notions when it comes to what java can offer, so your range of solutions it's a little bit limited.
Call userInput.nextLine(); just after while:
...
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
userInput.nextLine();
...
The issue is, that once you enter intput, which can not be interpreted as an int, userInput.hasNextInt() will return false (as expected). But this call will not clear the input, so for every loop iteration the condition doesn't change. So you get an infinite loop.
From Scanner#hasNextInt():
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
The fix is to clear the input if you came across invalid input. For example:
} else {
System.out.println("Invalid input. Please, enter a number.");
userInput.nextLine();
}
Another approach you could take, which requires less input reads from the scanner, is to always take the next line regardless and then handle the incorrect input while parsing.
public static int getSumOfInput() {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
String input = userInput.nextLine();
try {
int convertedInput = Integer.parseInt(input);
System.out.println("Number " + convertedInput + " added to the total sum.");
sumOfNums += convertedInput;
counter++;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please, enter a number.");
}
}
return sumOfNums;
}
I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.
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);
}
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.