I am relatively new to java and this is my first time working with if else statements. I was attempting to make a basic game in which the user guesses a number between 1-3, and the program tells them if they are right or wrong. However, when I go to execute the program, when I type 1, the program does not respond and I have to use ctrl-E to end it. What am I doing wrong? When I enter values aside from 1, the program executes as I want it to by printing "Goodbye."
Here is my code:
import java.util.*;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
Random rand = new Random();
System.out.println("Hey there! Want to play a game?");
System.out.println("\tIf yes, type 1");
System.out.println("\tIf no, type 2");
int ans1 = game.nextInt();
if (ans1 == 1) { // This is true, yet when I type 1, nothing happens.
int randomNum = rand.nextInt((3 - 1) + 1) + 1;
int guess = game.nextInt();
System.out.println("Great! I am thinking of an integer between 1 and 3. Guess what it is?");
if (guess == randomNum) {
System.out.println("Congradulations! You guessed correctly! The number was" + randomNum);
} else {
System.out.println("Sorry, your guess was incorrect. The number I was thinking of was" + randomNum);
}
} else {
System.out.println("Goodbye.");
}
}
}
This is my first time posting here, so I apologize if this question has been answered elsewhere.
Because if ans1=1, then it expects another input from user and checks if the guess and another input are same.
This is second input that it is waiting for
int guess = game.nextInt();
Input any number ,if the random number generated is equal to the number you added second time, it will return "Congradulations! You guessed correctly! The number was" else "Sorry, your guess was incorrect. The number I was thinking of was" with number
Instead of:
int guess = game.nextInt();
System.out.println( "Great! I am thinking of an integer between 1 and 3. Guess what it is?" );
You should have them reversed.
System.out.println( "Great! I am thinking of an integer between 1 and 3. Guess what it is?" );
int guess = game.nextInt();
Related
I tried to put together a simple guess my number game. You input a number, the computer outputs a random number, and tells you how far off you were. There aren't any errors in the code according to intellij, but it won't run. Here's my code:
import java.util.Scanner;
import java.util.Random;
public class ThinkJava {
//guess my number
public static void main(String[] args) {
//random number generator
Random random = new Random();
int number = random.nextInt(100) + 1;
Scanner in = new Scanner(System.in);
int guess = in.nextInt();
int difference = guess - number;
System.out.println("I'm thinking of a number 1-100 (including both). Can you guess what it is?");
in.nextInt();
System.out.println("Your guess is: " + guess);
System.out.println("The number I was thinking of was: " + number);
System.out.println("You were off by: " + difference);
}
}
Your code should run without any problem (it does for me), but not with the expected behaviour. Your game prompts for the number guess before any message is displayed:
int guess = in.nextInt();
Then, you have another prompt after the first message which requires another user input to continue:
System.out.println("I'm thinking of a number 1-100 (including both). Can you guess what it is?");
in.nextInt();
System.out.println("Your guess is: " + guess);
When you enter a second number at this point the program will display the last messages, but without taking into account the last input (as it was not assigned to a variable), and the guess and the difference info will reference the first number entered, making it confusing.
You should get rid of the second prompt and replace it with the first one, moving it (as well as the subsequent line which calculates the difference, as this depends on the first one).
Also, you should close() the Scanner when you are not using it anymore, to release the resource.
So, finally:
Scanner in = new Scanner(System.in);
System.out.println("I'm thinking of a number 1-100 (including both). Can you guess what it is?");
int guess = in.nextInt();
int difference = guess - number;
System.out.println("Your guess is: " + guess);
System.out.println("The number I was thinking of was: " + number);
System.out.println("You were off by: " + difference);
in.close();
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'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'm quite new to programming so excuse my basic and limited understanding. Essentially, I am creating a Memory Game for a school project. I want to do 2 do-while loops in a for loop that works like this: the user will be prompted to enter a 4 random letters which will be done in the first do-while loop and the second do-while loop will ask the user to re-input the phrase that they had initially entered.
So my first question is, why does only the first do-while execute? I'm assuming that the for loop executes the first-do-while and than repeats based on my parameters therefore the second one will never execute but, I'd appreciate any help understanding why, and reformatting my program accordingly perhaps.
My second question is that, I want to have a sort of score counter that nets the user 10 points for every correctly guessed letter in the correct sequence and deduct 10 for every incorrect character in the wrong sequence. How would I go about doing so, and what may I have to utilize to make this possible?
Lastly, I would appreciate if anyone could point towards a way of concealing the letters that the user inputs.
Any other suggestions to make my program more efficient would be greatly appreciated!
import java.util.Scanner;
import java.lang.String;
public class MemoryGame {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int choice;
System.out.println("This is a M E M O R Y G A M E");
System.out.println("Press '1' for instructions");
System.out.println("Press '2' to play");
choice = input.nextInt(); //Checks user selection and redirects
if (choice == 1) {
Instructions();
} else {
playGame();
}
input.close();
}
public static void Instructions() { //Instructions method
int choice;
Scanner input = new Scanner(System.in);
System.out.println("This is a memory game. Below are a few instructions on how to play as well as few hints, and tricks");
System.out.println("> Players wlll be given a input box to input a given number of letters or numbers depending on the stage level.");
System.out.println("> To progress and gain points, users must sucessfully recall the set phrase that they have inputted.");
System.out.println("> Based on the number of correct letters, users will gain points and progress through a set of levels that increase in difficulty.");
System.out.println("> Upon making 3 incorrect character selections users will be displayed a 'Game Over' screen from which they may:");
System.out.println("1. Head to the main menu");
System.out.println("2. View the instructions");
System.out.println("3. Play again");
System.out.println("If users successfully oomplete 5 stages with no errors, they will be prompted a challenge level in which more characters will be required");
System.out.println(" ");
System.out.println("1. Press '1' to return to play");
choice = input.nextInt();
if (choice == 1) {
playGame();
}
input.close(); //Closes input.
}
public static void playGame() {
int userNumbers1;
int userNumbers2;
String userLetters1;
String userLetters2;
int scorePlayer;
int livesPlayer = 3;
int stagePlayer = 4;
int stageGeneral = 1;
Scanner input = new Scanner(System.in);
System.out.println("This is the M E M O R Y G A M E");
System.out.println("Stage 1 initializing . . .");
System.out.println("Please enter " + stagePlayer + " letters of your choice.");
for (int i = 0; i <= 10; i++) {
do {
userLetters1 = input.nextLine();
userLetters1 = userLetters1.toLowerCase(); userLetters1.trim();
if (userLetters1.length()==stagePlayer) {
System.out.println (". . .!");
stagePlayer = stagePlayer + 2;
stageGeneral = stageGeneral + 1;
} else {
System.out.println("Please enter " + stagePlayer + " letters");
}
}
while ( userLetters1.length() != stagePlayer);
do {
userLetters2 = input.nextLine();
userLetters2 = userLetters2.toLowerCase(); userLetters2.trim();
if (userLetters2.length()==userLetters1.length() && userLetters2.equals (userLetters1)) {
System.out.println (". . .");
System.out.println ("Great job!");
System.out.println("Stage " + stageGeneral + " initializing . . .");
System.out.println("Please enter " + stagePlayer + " letters of your choice.");
} else {
System.out.println ("Please enter " + userLetters1.length() + "letters that were previously entered.");
}
}
while ( userLetters1.length() != userLetters2.length());
}
}
}
Don't assume. Debug instead. Look what happens line by line and determine the reason the first do lop never exits. It if exited I see no reason why the second one didn't execute.
For second question I'd enciurage to read String class documentation. All you need is to iterate through characters and react accordingly to results of copmarisions.
In console, to hide previous user input you could clear the screen like:
Runtime.getRuntime().exex("cls);
I have the majority of my program finished, but now that I have most of the code it is tough to find the errors. I have multiple errors at the moment, but the main error I really need help with is that my program will loop the same guess over & over if it is correct. It is in an infinite loop, & I cannot find where it is. This has also brought to my attention that my program will go into negative guesses as it is supposed to end when it gets to 0. Some other errors that would be nice to get help with is 1) it shows a correct guess as an incorrect guess 2) it can only replace one letter in the secret word if there are multiple it will give me an error & end the program. & 3) if I enter 9 to quit, it does not quit.
Thanks in advance for any help. I can add code if needed ( I am only posting the main body ATM.)
public static final int DICTIONARY = 15000;
public static final int GUESSES = 8;
public static final int SECRETLENGTH = 20;
public static void main(String[] args) {
int usedSize = 0, randomWord, guesses = GUESSES;
String word, secretWord, guess, incorrectGuess, correctWord, playAgain;
char letter;
try
{
// Set up connection to the input file
Scanner hangmanDictionary = new Scanner(new FileReader("dictionary.txt"));
String [] dictionary = new String [DICTIONARY];
while (usedSize < DICTIONARY && hangmanDictionary.hasNextLine()) {
dictionary[usedSize] = hangmanDictionary.nextLine();
usedSize++;
}
kbd.nextLine();
clearScreen();
randomWord = pickRandom(DICTIONARY);
word = dictionary[randomWord];
secretWord = secret(word);
//comment out when done testing
System.out.println(word);
System.out.println("Here is the word to guess: " + secretWord);
System.out.println("Enter a letter to guess, or 9 to quit.");
guess = kbd.next();
do {
while (!guess.equals("9") || !(guess.equals(word) && guesses > 0)) {
letter = guess.charAt(0);
incorrectGuess = "";
incorrectGuess += letter;
if (word.indexOf(letter) < 0) {
guesses--;
System.out.println("Incorrect guesses: " + incorrectGuess);
System.out.println("Number of guesses left: " + guesses);
System.out.println("Enter a letter to guess, or 9 to quit.");
guess = kbd.next();
}
else {
//FINSH THIS
correctWord = correctWord(guess, word, secretWord, letter);
System.out.println(correctWord);
System.out.println("Incorrect guesses: " + incorrectGuess);
System.out.println("Number of guesses left: " + guesses);
System.out.println("Enter a letter to guess, or 9 to quit.");
guesses--;
}
}
if (guess.equals("9")) {
System.out.println("Thanks for playing!");
System.exit(0);
}
if (guess.equals(word)) {
System.out.println("You won!");
}
if (guesses == 0) {
System.out.println("You are out of guesses.");
}
System.out.println("Play again? Y/N");
playAgain = kbd.nextLine().toUpperCase();
} while (playAgain.equals("Y"));
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
Here's my guess:
Did you forget to put guess = kbd.next(); if the user guessed a correct character?
The inner while loop is your main problem, i.e. think about what happens when you enter a valid letter (guess), in that case the first condition of the while loop OR condition is TRUE (assuming you don't have a 9 in your secret word), so the while loop is entered without entering the second part of the OR condition. After that you enter the else part of the IF statement (since it's a valid guess) but in the else part you're not asking for the next guess, so it returns to the start of the while loop with the same guess and hence infinite loop.
Similarly, if you enter 9 to exit !guess.equals("9") evaluates to FALSE, so the second part of the OR condition is entered, in the second part
!(guess.equals(word) && guesses > 0) evaluates to TRUE (unless the secret word contains a 9) so you enter the WHILE loop which is invalid. etc ...
Try to write small parts of the code using known parameters and then bring it all together, that way it'll be easier to construct and follow the logic.