I've made a program that asks the user for a number and then checks if it is equal, less or greater than a random number. A siple guessing game. It works perfectly but I would like to display the output on the same line as the input but I can't figure out how to do this.
Ok, I've picked a number between 1 and 100. What is your first guess?
Guess 1: 36
<
Guess 2: 50
>
Guess 3: 46
That is correct. The hidden number is 46.
This is how I want it to look like:
Guess 1: 36 <
Guess 2: 50 >
Guess 3: 46 That is correct. The hidden number is 46.
How do I do this? The cursor is moving down after the input when I use Scanner.nextInt();
This is my current code:
while (!isCorrect) {
System.out.print("Guess " + guessCount + ": ");
currentGuess = input.nextInt();
if (currentGuess == randomNumber) {
isCorrect = true;
System.out.println("That is correct. The hidden number was " + randomNumber);
}
else if (currentGuess > randomNumber) {
System.out.println(" >");
++guessCount;
}
else if (currentGuess < randomNumber) {
System.out.println(" <");
++guessCount;
}
}
That's not consistently possible. You could try echoing a \b backspace character, but that probably wouldn't work. Once the user types the new line, there is no way to take it off.
The best you are going to be able to accomplish is to re-echo the input.
while (!isCorrect) {
System.out.print("Guess " + guessCount + ": ");
currentGuess = input.nextInt();
if (currentGuess == randomNumber) {
isCorrect = true;
System.out.println("That is correct. The hidden number was " + randomNumber);
}
else if (currentGuess > randomNumber) {
System.out.println(currentGuess + " >");
++guessCount;
}
else if (currentGuess < randomNumber) {
System.out.println(currentGuess + " <");
++guessCount;
}
}
for the output:
Guess 1: 36
36 <
Guess 2: 50
50 >
Guess 3: 46
That is correct. The hidden number is 46.
If you really need to format your output like that you could try saving your input to an arraylist, clearing the screen, then printing all the previous inputs to the screen again.
List<Integer> foo = new ArrayList<Integer>();
while (!isCorrect) {
System.out.print("Guess " + guessCount + ": ");
guessCount++;
currentGuess = input.nextInt();
foo.add(currentGuess);
for(int a = 0; a < 50; a++) {
System.out.println('\n');
}
for(int i = 0; i < foo.size(); i++) {
currentGuess = foo.get(i);
System.out.print("Guess " + (i+1) + ": " + currentGuess);
if (currentGuess == randomNumber) {
isCorrect = true;
System.out.println(" That is correct. The hidden number was " + randomNumber);
}
else if (currentGuess > randomNumber) {
System.out.println(" >");
}
else if (currentGuess < randomNumber) {
System.out.println(" <");
}
}
}
To clear the screen I just printed out 50 blank lines.
A solution to clear the console is proposed here:
Java: Clear the console
however, it didn't work for me or Chris.
Related
When I run the code with the commented out portion, the program works as intended. After the first guess, it tells the user to try a higher or lower number. Without the commented out portion, the prompts only appear after the second guess.
I just started learning Java and the book I am following does not offer further explanation.
import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;
public class GuessAgain {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numGuesses = 0;
int randomNumber = new Random().nextInt(100) + 1;
int minbound = 1;
int maxbound = 100;
out.println(" ********** ");
out.println(" Welcome to the Guessing Game ");
out.println(" ********** ");
out.println();
out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
int inputNumber = keyboard.nextInt();
numGuesses++;
/*
if (inputNumber > randomNumber) {
out.println("Try a lower number!");
}
if (inputNumber < randomNumber) {
out.println("Try a higher number!");
*/
while (inputNumber != randomNumber) {
out.println();
out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
inputNumber = keyboard.nextInt();
numGuesses++;
if (inputNumber > randomNumber) {
out.println("Try a lower number!");
}
if (inputNumber < randomNumber) {
out.println("Try a higher number!");
}
}
out.println("You win after " + numGuesses + " guesses.");
keyboard.close();
}
}
This is because after the first guess you are entering the while loop, which starts with asking for a new guess before giving a hint.
First ask is outside of while loop, second is inside, afterwards comes the hint.
You need to print out the result before asking for the next input.
For example:
while (inputNumber != randomNumber) {
if (inputNumber > randomNumber) out.println("Try a lower number!");
if (inputNumber < randomNumber) out.println("Try a higher number!");
out.println();
out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
inputNumber = keyboard.nextInt();
numGuesses++;
}
I have a problem with my program.
Program is a HILO game which requires the user to guess a number between a range of a generated number.
The problem is that once i press 0 on my keyboard, it reveals the random number, and essentially must end the loop and ask whether the user wants to continue or end the program. Instead, it continues the loop, and whenever I press a letter on the keyboard it shows me an Exception error which describes and input Miss Match. Can some one guide me on how to fix it?, maybe I wrote the program wrong, I tried multiple ways, it still doesn't work as it supposed to work.
Thank you.
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class HILOGAME
{
public static void firstGame()
{
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
for (int exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.nextLine();
if (!choice.equalsIgnoreCase("x"))
{
Loop = true;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
Loop = false;
System.out.print("END OF GAME");
exit = 11;
}
}
if (number > answer)
{
System.out.println("TOO HIGH");
}
if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
}
}
}
}
}
EDIT 1:
This code is working perfectly for me i have tried running it:
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
int exit;
for (exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.next();
// HERE YOU ARE DOING THE WRONG THING
// What is the meaning of "not(!)" here ? !choice.equalsIgnoreCase("x")
// Remove "NOT(!)" from here your program will work as expected
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
else if (number > answer)
{
System.out.println("TOO HIGH");
}
else if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
// MADE CHANGES HERE
choice = input.next();
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
}
}
Please do copy-paste the code. Because it is working perfectly without any Exception..!!
My sample outputs:
SAMPLE 1:
Guess a number between 1 and 50 : 1
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 27
Enter x to continue to play or y to endgame
y
END OF GAME
SAMPLE 2:
Guess a number between 1 and 50 : 20
TOO HIGH
Guess a number between 1 and 50 : 19
TOO HIGH
Guess a number between 1 and 50 : 15
Your guess was correct
The number was: 15
You guess the number with: 3 guesses
Enter x to continue to play or y to endgame
x
A new numberGuess a number between 1 and 50 : 20
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 42
Enter x to continue to play or y to endgame
y
END OF GAME
Do let me know if there is any problem.
Well, if you wish to end a loop, you could use the break; command. It jumps out of a while or for loop. So you could use this if the number is 0:
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter 'x' to continue to play or y to endgame");
choice = input.nextLine();
if(choice == "y")
{
break;
}
and add:
if(choice == "y") {break;} to the very end of the while(!Loop) loop.
And with the time when the answer is correct, you set Loop to false, which means !Loop would evaluate to true. You should change Loop = false to Loop = true when they decide to continue the game.
a small modification
public class HILOGAME {
public static void firstGame() {
final int range = 50;
int answer;
int number;
int guessNum = 0;
String choice = "";
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
if (number == answer) {
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
} else {
System.out.println("you entered a wrong value");
System.out.println("do you really want to try again? press y to continue or other alphabet to exit");
choice = input.next();
playAgain(choice);
}
}
public static void playAgain(String choice) {
if (choice.equalsIgnoreCase("Y")) {
firstGame();
} else {
System.out.println("you chose to quit");
System.exit(0);
}
}
I have a quick question about this HiLo game that I have been trying to fix from a while now. When I run the program it counts guesses outside of the 0-10 range, but I don't want it to do that. How do I fix that? Here is my code.
import java.util.Random; // Random number generator class
import java.util.Scanner; // reads user inputs
public class HiLo
{
public static void main(String[] args)
{
// declare variables
final int MAX = 10;
int answer, guess;
int numberOfTries = 0;
String again;
Scanner Keyboard = new Scanner(System.in);
do
{
System.out.print(" I'm thinking of a number between 0 and "
+ MAX + ". Guess what it is: ");
guess = Keyboard.nextInt();
// guess
Random generator = new Random(); // Random number generator. 0 to 10.
answer = generator.nextInt(MAX) + 1;
if (guess > 10) // if guess is bigger than 10 then error message
{
System.out.println("ERROR – Your guess is out of the range 0 to 10.");
}
if (guess < 0) // if guess is smaller than 0 then error message
{
System.out.println("ERROR – Your guess is out of the range 0 to 10.");
}
while (guess != answer) // If guess is not the answer
{
if (guess > answer) // If guess is more than the answer
{
System.out.println("You guessed too high! \nTry again:");
guess = Keyboard.nextInt();
}
if (guess < answer)// If guess is less than the answer
{
System.out.println("Too Low! \nTry again:");
guess = Keyboard.nextInt();
}
numberOfTries = numberOfTries + 1;
}// end of the loop
// display result
if (guess == answer)
{
numberOfTries += 1;
System.out.println("YOU WIN!");
System.out.println("It took you " + numberOfTries + " tries!");
System.out.println();
System.out.print("Do you want to play again(Y/N)?");
}
Keyboard.nextLine(); // skip over enter key
again = Keyboard.nextLine();
numberOfTries = 0;
} while (again.equalsIgnoreCase("Y"));
} // end of class
} // end of main
You report the error but you don't continue; (and use a logical ||) like this
if (guess < 0 || guess > 10) {
System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
again = "Y"; // <-- make sure we'll re-evaluate.
continue; // <-- Add then skip the rest of the loop body
}
Hello I am a beginner Java programmer. My Program keeps ending when I put the correct number in (with out printing the message ), or it wont go from a lower number to a higher one with out ending?
Can someone tell me what I am doing wrong?
package week3;
import java.util.Scanner;
public class Week3 {
public static void main(String[] args) {
Scanner In = new Scanner(System.in);
int Guess ;
int count = 0;
count++;
int c = 55;
System.out.println("Welcome to the Higher / Lower game! Try to guess the"
+ "number between 1 and 100. ");
System.out.print("Enter your guess: ");
Guess = In.nextInt();
if(Guess == c)
{
System.out.println("The number was 55 you guessed correctly! "
+ " it took you " + count +" tries");
}//end if
while (Guess < 1)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
Guess = In.nextInt();
}//End while < 1
while (Guess > 100)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
Guess = In.nextInt();
}//end while <100
while (Guess >= 56)
{
System.out.println("The number is lower.");
Guess = In.nextInt();
} //end while over 55
while (Guess <= 54)
{
System.out.println("The number is higher.");
Guess = In.nextInt();
}//end while lower than 55
}//end main
}//end class
I can see the problem, but you would be better off trying to find it yourself. (Or having another go ...)
Hints:
Try hand-executing the code. Pretend you are the computer, and use a pencil and paper to simulate what it would do.
Have you tried using a debugger?
Some of the comments are good hints too.
While I have your ear, you also should pay attention to your programming style. And one universal style rule for Java is that variables should start with a lower-case letter. Your In and Guess variables violate this.
System.out.println("Welcome to the Higher / Lower game! Try to guess the"
+ "number between 1 and 100. ");
while (true) {
System.out.print("Enter your guess: ");
Guess = Integer.parseint(In.nextLine());
if(Guess == c)
{
System.out.println("The number was 55 you guessed correctly! "
+ " it took you " + count +" tries");
break;
}
if (Guess < 1)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
}
if (Guess > 100)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
}
if (Guess >= 56)
{
System.out.println("The number is lower.");
}
if (Guess <= 54)
{
System.out.println("The number is higher.");
}
}
}
}
Hopefully this gives you the idea of using the while loop.
The structure of your program is incorrect.
You only need one while loop. Begin your program with a while loop, and continue with conditions, such that:
boolean numFound = false;
while (!numFound) {
//conditions
}
I want to do a switch in while loop where at the break of every switch statement the while loop stops and ask for an input like F, R, C, Q. The statement below works but the statement does not break. Please help
public static void main(String[] args) throws IOException {
// start both with 1 point
int goodTotal = 50;
int monTotal = 50;
// input switch statement
while (goodTotal > 0 && monTotal > 0) {
System.out.print("Type a letter: ");
System.out.println("\n");
System.out.print("F: Go out and Fight ");
System.out.println("\n");
System.out.print("R: Rest ");
System.out.println("\n");
System.out.print("C: Check Stats ");
System.out.println("\n");
System.out.print("Q: Quit ");
int input = System.in.read();
System.out.println("You typed: " + (char) input);
switch (input) {
case 'f':
System.out.println("Continue the game");
break;
case 'r':
System.out.println("Players should rest");
break;
case 'c':
System.out.println("Checking the status of the game");
System.out.print("Goodman has " + goodTotal + " points and Monster has " + monTotal + " points");
System.out.println("\n");
break;
case 'q':
System.out.println("Game over");
System.exit(input);
break;
default:
System.out.println("Invalid selection");
break;
}
// Set value of minimum and maximum damage
int minDmg = 2;
int maxDmg = 15;
// Get random number;
int damage = minDmg + Double.valueOf(Math.random() * (maxDmg - minDmg)).intValue();
int damage2 = minDmg + Double.valueOf(Math.random() * (maxDmg - minDmg)).intValue();
// remove value of damage from started value to get total value remaining
goodTotal = goodTotal - damage;
monTotal = monTotal - damage2;
// print message if still in the game
if (goodTotal > 0) {
System.out.println("Goodman has " + goodTotal + " points left. Not bad, Man! ");
}
// if Goodman survives round 2 print a message of encouragement
if (goodTotal > 0 && count > 1 && count <= 2) {
System.out.print("This is encouraging. Goodman has lasted past roundhh " + count + ". ");
// print new message if Goodman passes round 3
} else if (goodTotal > 0 && count == 3) {
System.out.print("Goodman is as strong as Samson. He has lasted round " + count
+ " and still looks strong.");
System.out.print(" 10 hit points has been added to your total");
}
if (monTotal > 0) {
System.out.println("Wait, Monster has a total of " + monTotal + " points and is still in the game");
}
// exit if have less than 0 point, and print game over. Congratulate the winner
if (goodTotal < 0) {
System.out.println("Goodman you are out of the game");
System.out.println("The monster will take over the village. This is sad");
System.out.println("Game Over!");
} else if (monTotal < 0) {
System.out.println("Goodman has been victorious");
System.out.println("The monster is dead. The people live!!!!");
System.out.println("Game Over!");
}
System.out.println("This is the end of round " + count + " ");
System.out.println("\n");
count = count + 1;
}
}
Use a label on the loop:
loop: while (goodTotal > 0 && monTotal > 0) {
// ...
switch (input) {
case 'f':
// ...
break loop;
case 'r':
// ...
break loop;
// ...
}
// ...
}
You should use labelled breaks.
Although it probably is better to rewrite the code in a way that doesn't need them, as they're not very easy to read.
input is of type int, but the case labels are character literals ( i.e., f,r,c,q). Why don't you just make the input also a char type ?
char input = System.in.read();