This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
so, for my Java class I need to make a HiLo game. I figured the game out on my own, but I wanted to take it a step further, and after the user completes the game(guesses the right number) I want to ask them if they would like to play again.
The problem is, I can't seem to figure out exactly how. I have tried several things and at the moment I'm trying to get them to enter either yes or no to continue playing the game. If someone could help me figure out what I'm doing wrong and explain it to me, that would be great. Thanks!
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int answer, guess;
answer = generator.nextInt(101);
System.out.println("Lets play a game. Guess the number(0-100): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
}
if (guess == answer)
System.out.println("You got it! The number was " + answer);
//after initial game finishes, we ask if they want to play again.
System.out.print("Want to play again? ");
String again = scan.nextLine();
while (again != "no"){
System.out.println();
System.out.print("Great! lets play again.");
System.out.println("Take a guess(0-100 inclusive): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
if (guess == answer)
System.out.println("Your got it! The number was " + answer);
System.out.println("Want to play again? (0 for no, 1 for yes): ");
again = scan.nextLine();
}
}
System.out.println("Thanks for playing!");
}
}
The != operator does not check if two strings contain the same characters. What you want to do is:
while (again.equals("yes")) {
...
}
You should also try to put your game code inside another loop, so at the end of the game (still inside the loop) you can ask the player if they want to play again. If yes, the loop has to be executed again, otherwise it stops.
This way the player can play an infinite number of games and you don't need to duplicate your game code. Example (to get an idea of what the structure could look like):
// start with "yes" in order to enter the game loop initially
String again = "yes";
while(again.equals("yes")) {
answer = generator.nextInt(101);
System.out.println("Lets play a game. Guess the number(0-100): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
}
System.out.println("You got it! The number was " + answer);
// ask them if they want to play again. only "yes" will start another game
System.out.println("Do you want to play again (yes/no)?");
again = scan.nextLine();
}
Related
I've just started learning programming for the first time and I am working through Java to start. I am doing a common coding exercise of programming a guessing game using loops and conditionals. My program is required to do the following:
Pick a random number between 1 and 100
Repeatedly prompt the user to guess the number
Report to the user that he or she is correct or that the guess is high
or low after each guess
Offer the user the option to quit mid-game
Count the number of guesses in a game and report the number upon a correct guess
Ask the user if they want to play again upon a successful game
I have been a little bit shaky with loop syntax so far and need some help with my program because there are a lot of issues I don't know how to fix. Would anyone be kind enough to lend me a hand? Please forgive the many probably obvious mistakes.
import java.util.Scanner;
import java.util.Random;
public class Guess
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess = 0, count = 0;
String another = "y";
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
Scanner scan = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and " + MAX
+ ". Guess what it is: ");
guess = scan.nextInt();
while (another.equalsIgnoreCase("y"))
{
while (guess != answer)
{
while (guess > MAX || guess < 1)
{
System.out.println("Invalid input. Please re-enter a number"
+ " between 1 and " + MAX + ":");
guess = scan.nextInt();
}
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
}
else if (guess > answer)
{
count++;
System.out.println("You guessed too high. Guess again? Y/N:");
another = scan.nextLine();
}
else if (guess < answer)
{
count++;
System.out.println("You guessed too low. Guess again? Y/N:");
another = scan.nextLine();
}
}
}
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
}
One problem is that you're not letting the user quit midway through the game because even if the user guesses a number within the 1 to 100 range and doesn't get the right answer, his or her answer to Guess again: Y/N: won't be checked since the current loop it is in only compares guess to answer, never another. Therefore, you'll end up being in an infinite loop in this case because if the user guesses 57 when the answer is 50, you'll just continuously prompt the user if he or she wants to guess again.
My recommendation would be to remove the second while loop
while (guess != answer)
{
//other stuff
}
and place the code inside that loop into the outside while loop
while(another.equalsIgnoreCase("y")){
//other stuff
}
And if you want the user to be able to play again, I would recommend putting this snippet of code you had earlier inside the if statement where you check if the user has guessed correctly,
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
This way, if the user wins the game, their choice to play again will be checked in the while loop. One last thing I would recommend is moving this line
guess = scan.nextInt();
inside the while loop that checks another so that if the user wants to play again, the game will prompt the user for a guess.
I am writing a program where the user enters a number and the computer guesses the number.
I'm having trouble with my else/if statement inside of my while loop. The problem is it prints out "guess higher" but the computer does not always guess higher. I'm not sure how to go about this problem.
while(computerGuess != userGuess) {
if(computerGuess > userGuess) {
System.out.println("Guess lower: ");
computerGuess = guess.nextInt(userGuess);
System.out.println(computerGuess);
}else if(computerGuess < userGuess) {
System.out.println("Guess higher: ");
computerGuess = guess.nextInt(101);
System.out.println(computerGuess);
}
amountTries++;
}
The problem is it prints out "guess higher" but the computer does not
always guess higher. I'm not sure how to go about this problem.
You are specifying a hard-coded limit of 101 for the random number generation. But in the case where the computer guess is smaller than the user value, you need to have a random number generated between the computer guess and the user guess.
Replace
computerGuess = guess.nextInt(101);
with
computerGuess = guess.nextInt(userGuess - computerGuess) + computerGuess + 1;
If you are trying to build a program where computer guesses the number by binary search logic then your code is not going to work. Following code will perform binary search kind of logic.
int i=0;int j=101;
while(computerGuess != userGuess) {
if(computerGuess > userGuess) {
j=computerGuess;
System.out.println("Guess lower: ");
computerGuess = guess.nextInt(j);
System.out.println(computerGuess);
}else if(computerGuess < userGuess) {
i=computerGuess;
System.out.println("Guess higher: ");
//computerGuess = guess.nextInt(101);
computerGuess = guess.nextInt(j - i) +i;
System.out.println(computerGuess);
}
amountTries++;
}
PS: Not tested for corner cases. Code is just to provide a basic idea.
This is my code below, i need to insert a play again function and a method that allows me to save the user name, number of attempts, number of successful attempts and the players best score to a text file! I have to repeat this bit of coursework to get back into my second year of university so any pointers about the code in generally would be greatly appreciated. I was never that good at programming so i'm badly stuck. This is my first time posting on this site as well due to recommendations of a friend so thanks in advance
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class GuessingGame3 {
public static void main(String[] args)
{
Random generator = new Random(); //This is were the computer selects the Target
int guess;
int count = 0;
int Target;
String userName;
int answer;
boolean play = true;
int attempt = 6;
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)
{
Target = generator.nextInt(100) + 1;
System.out.println("Can you guess the number i'm thinking off? You will have "+ attempt +" 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();
count++;
attempt -= 1;
if (guess > Target)
System.out.println("Sorry! Your guess was too high! You have "+ attempt +" attempts left!"); //This is to help the player get to the answer
else
if (guess < Target)
System.out.println("Sorry! Your guess was too low! You have "+ attempt +" attempts left!"); //This is to help the player get to the answer
}
while(guess != Target && count <6);
if(guess == Target) {
System.out.println("Congratulations "+ userName + ", it took you "+ count +" attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
}
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
}
{
while(guess = Target || count > 6);
System.out.println("Would you like to play again "+ userName +"? [Y?N]:\n");
Answer = answer.nextLine();
if (Answer = "Y")
play = true;
else
if (Answer = "N")
System.out.println("Thanks for playing "+ userName +" :)! Please come back soon!");
}
break;
}
}
}
As the user above noted, you need this to be Answer == Y. YOu should not use strings, but characters. You should also use 'ToUpperCase()' to ensure that it will still work if the user inputs 'y' I recommend using .nextChar() instead of nextLine(), in case the user accidentily inputs a string with more than one character. for example if they bump the t button while pressing y.
I have a little problem with this do while loop; when I run the program it is working, at least partially, what I mean is first you need to make a choice for convertion from C to F or from F to C and after you enter the values the program stops what I want to do is to keep asking for values until you enter 3. I tried to do it with a do while loop but it is not working so if someone has any ideas I would be grateful. Here is the code:
import java.util.Scanner;
public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}
Like in your other question, here you're scanning for input before prompting the user for input.
You need to remove the second line below:
System.out.println("Conversion table: ");
int choice = input.nextInt();
do
With your code as is, it outputs
Conversion table:
and then blocks waiting for input. Whereas you want it instead to continue into the while loop and output
1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:
Make a choice between 1 - 3
before blocking to scan for input.
As is, if you enter any number at the first block, your program enters the loop and behaves as you wanted. So you're nearly there!
The code does work. the problem is most likely the
int choice = input.nextInt();
before the do
Remove this, and change
choice = input.nextInt();
to
int choice = input.nextInt();
Besides the fact that you have: int choice = input.nextInt(); outside of the loop which is unnecessarily getting input before showing the menu, it seems to all work relatively fine. You can just declare int choice inside the loop where you have choice = input.nextInt(); (ie. just change that to intchoice = input.nextInt();).
I tested your code, and it works fine if you change the line int choice = input.nextInt(); (just before your do{} while() block) into int choice;.
As others have already mentioned, you should not read input before your do{} while() block, since the question has not been asked yet.
you forgot the break; after your default case
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
how to create a counter in a dr java program
this is the code that I am working on...
I would like to know how to reset the interactions window after every question is asked so that the window is clear for the next question to be shown to the user but I do not want the Score to be reset either so that I can display the score at the end. I am looking for the correct syntax and code to do this.
//Neel Patel
//Friday October 9th, 2009
/*This is a quiz program that will ask the user 10 questions. the user will answer
* these questions and will be scored out of 10.*/
class Quiz
{
public static void main (String args[])
{
//Instructions
System.out.println("instructions");
System.out.println(" ");
System.out.println("1. You wll be asked ten questions through out the quiz.");
System.out.println("2. The first question will appear, you will have to answer that question for the next question to appear.");
System.out.println("3. When you answer the last question you will be told your score.");
System.out.println(" ");
System.out.println("welcome to the basketball quiz.");
int Score=0;
// question 1
System.out.println(" ");
System.out.println("Question 1. ");
System.out.println("How tall is a basketball hoop? ");
System.out.println("Type in Answer here:");
String Question1= In.getString();
if (Question1.equalsIgnoreCase("10 Feet"))
{
Score++;
System.out.println("Correct!");
}
else
{
System.out.println("you got this questions wrong");
}
// question 2
System.out.println(" ");
System.out.println("Question 2. ");
System.out.println("Who invented basketball? ");
System.out.println("Type in Answer here:");
String Question2= In.getString();
if (Question2.equalsIgnoreCase("James Naismith"))
{
Score++;
System.out.println("Correct!");
}
else
{
System.out.println("you got this questions wrong");
}
// question 3
System.out.println(" ");
System.out.println("Question 3. ");
System.out.println("Who is the only person in the history of the NBA to average a triple double for an entier season?");
System.out.println("Type in Answer here:");
String Question3= In.getString();
if (Question3.equalsIgnoreCase("Oscar Robertson"))
{
Score++;
System.out.println("Correct!");
}
else
{
System.out.println("you got this questions wrong");
}
// question 4
System.out.println(" ");
System.out.println("Question 4. ");
System.out.println("how many players was the first basketball game played with?");
System.out.println("Type in Answer here:");
String Question4= In.getString();
if (Question4.equalsIgnoreCase("9 on 9||18"))
{
Score++;
System.out.println("Correct!");
}
else
{
System.out.println("you got this questions wrong");
}
}
}
You need to use a loop of some sort. So you can start by creating arrays to store the questions and answers like this:
String[] questions = {" \nQuestion 1. \nHow tall is a basketball hoop? \nType in Answer here:",
" \nQuestion 2. \nWho invented basketball? \nType in Answer here: "};
String[] answers = {"10 Feet", "James Naismith"};
int score = 0;
String ans = "";
Then you can write a loop like this:
for(int i = 0;i < questions.length; i++){
System.out.println(questions[i]);
ans= In.getString();
if (ans.equalsIgnoreCase(answers[i]))
{
System.out.println("Correct!");
score++;
}
else
{
System.out.println("you got this questions wrong");
}
}
System.out.println(score);
And finally to clear the screen itself you cannot do that directly in Java but you may be able to run the cls command (assuming you run Windows) but that makes your code platform specific.
Runtime.getRuntime().exec("cls");
One brute-force (and, unlike cls, platform-independent) method for clearing the console would be to print a whole bunch of newliness to the console. This approach could have the added benefit of being seen as befitting an 11th grade CS project.