Do i need a continue command or not. Why? - java

I am making a random generated number game. Computer randomizes a number 1-50 and user needs to guess that number in order to win. I need some help with using continue command in one line where program asks user to play the game over or quit the game.
Today we learned about continue and break commands. Professor made a little game to showcase using of continue and break. I copied the code to analyse it and deleted an continue command in one line just to see will it still work, and it did. Why did it work? I have marked the line with //<---HERE
while (true) {
Scanner input = new Scanner(System.in);
int randomNum = (int) (Math.random() * 50) + 1;
boolean found = false;
System.out.println("A number 1-50 is picked, try to guess it!");
System.out.println("--Testing purpose only--" + randomNum);
for (int i = 1; i < 6; i++) {
System.out.print(i + ". Try: ");
int chosen = input.nextInt();
if (chosen == randomNum) {
found = true;
System.out.println("You've guessed it");
break;
} else if (chosen < randomNum) {
System.out.println("Number you are guessing is higher");
} else {
System.out.println("Number you are guessing is lower");
}
}
if (found) {
System.out.println("Victory");
System.out.println("Guessing number was: " + randomNum);
} else {
System.out.println("Defeat! Guessing number was: " + randomNum);
}
System.out.print("Start over? (type \"yes\")");
String s = input.next();
if (s.equalsIgnoreCase("yes")) {
System.out.println("**************************");
**continue**; //<---HERE
} else {
System.out.println("End.");
break;
}
}
I am expecting an error if there is no continue command in marked place but there is no error and the program works fine.

It is the last statement of your infinite while loop. It has no effect whatsoever.

The continue line does not do anything in this case as it is the last statement in the loop.

It makes no sense for your code to generate an error just because you removed continue, the continue command will let you tell your program to skip to the next iteration. So without continue your code continues to execute normally.

Related

Java High-Low Guessing Game Looping Errors

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.

java if statement not executing

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();

Correct user input not matching array values

I've written a portion of code to take a user input, match it to a string value and then use a related double value to make calculations:
double [] currency = new double[] {0.05,0.10,0.20,0.50,1.00,2.00,5.00,10.00,20.00,50.00,100.00};
String [] currencytext = {"$0.05","$0.10","$0.20","$0.50","$1.00","$2.00","$5.00","$10.00","$20.00","$50.00","$100.00"};
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < currencytext.length; i++) {
boolean valid = false;
while(!valid){
System.out.format("$%.2f remains to be paid. Enter coin or note: ",sum);
String payment = keyboard.next();
if(payment.equals(currencytext[i])){
sum = sum - currency[i];
if(sum == 0) {
System.out.print("You gave " + payment);
System.out.print("Perfect! No change given.");
System.out.print("");
System.out.print("Thank you" + name + ".");
System.out.print("See you next time.");
}
}
if(!(payment.equals(currencytext[i]))) {
System.out.print("Invalid coin or note. Try again. \n");
}
if(payment.equals(currencytext[i]) && currency[i] > sum){
System.out.print("You gave " + payment);
System.out.print("Your change:");
}
}
}
The problem is that when it gets to user input, it doesn't match any string values except for $0.05. It seems to me like its not iterating through the array properly but I can't figure out why. Is anyone able to see a problem here?
This is a possible solution for your problem
Scanner keyboard = new Scanner(System.in);
double [] currency = new double[] {0.05,0.10,0.20,0.50,1.00,2.00,5.00,10.00,20.00,50.00,100.00};
String [] currencytext = {"$0.05","$0.10","$0.20","$0.50","$1.00","$2.00","$5.00","$10.00","$20.00","$50.00","$100.00"};
String payment = keyboard.next();
double sum = 100; // <- Working example - Read sum from keyboard entry
while (sum > 0) {
boolean paymentFound = false;
for (int i = 0; i < currencytext.length; i++) {
if (payment.equals(currencytext[i])) {
sum = sum - currency[i];
paymentFound = true;
if (sum == 0) {
System.out.println("You gave " + payment);
System.out.println("Perfect! No change given.");
// System.out.print("Thank you" + name + ".");
System.out.println("See you next time.");
break;
} else if (sum < 0) {
System.out.println("You gave " + payment);
System.out.println("Your change:" + (-1 * sum));
break;
}
}
}
if (!paymentFound) {
System.out.println("Invalid coin or note. Try again. \n");
}
if (sum > 0) {
System.out.format("$%.2f remains to be paid. Enter coin or note: ", sum);
payment = keyboard.next();
}
}
while-loop will continue until the payment is fullfilled.
for-loop traverse the arrays until a suitable payment is found
If suitable payment is found we substract it from sum. We use break to exit the for-loop in both cases. There is no need to keep searching.
If no suitable payment is found [!paymentFound], we keep on asking.
if (!paymentFound) {
System.out.println("Invalid coin or note. Try again. \n");
}
if (sum > 0) {
System.out.format("$%.2f remains to be paid. Enter coin or note: ", sum);
payment = keyboard.next();
}
The program will end when (sum < 0), in which case the while-loop exits.
I have use println instead of print to improve message legibility.
Too many flaws to point out.
However,
When the currencytext[i] does not match payment, it executes this code:
System.out.print("Invalid coin or note. Try again. \n");
System.out.format("$%.2f remains to be paid. Enter coin or note: ",sum);
payment = keyboard.next();
So, it executes this for all the times that your input does not match currencytext[i].
And, in this block, you have
payment = keyboard.next();
So, it asks for new input, in this block itself. Hence, you get the said output for all inputs except $0.05.
As far as $0.05 is concerned, your first if block executes successfully, and prints no output. So, it moves to the next iteration of the while loop, where again, payment remains the same ($0.05), but currencytext[i] becomes $0.10. SO they do not match, and you get the said output.
How to correct this:
With this code, you need to do a lot of corrections.
I suggest you again start from scratch.
If it doesn't fit, it sets valid to true, so the code just has the chance to check against the first item at currencytext[0], which is $0.05. Then !payment.equals(currencytext[i]) is also true, and your code prints the lines there. Your else ifs are also not properly nested.
I don't know how you are reading input. One improvement you can do is write reading input code in for loop.
Scanner scanner = new Scanner(System.in);
for (... ) {
....
String payment = scanner.nextLine();
....
}

Java Looping issue in Hangman program(Cant find)

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.

unable to get loop to work properly

import java.util.Random;
import java.util.Scanner;
public class addinggamedowhile
{
public static void main (String[]args)
{
Random r = new Random ();
Scanner s = new Scanner(System.in);
int x = r.nextInt(20)+1;
int y = r.nextInt(20)+1;
int sum = x + y;
int guess;
System.out.println("===========");
System.out.println("Adding Game");
System.out.println("===========");
System.out.println();
int tries = 0;
for (int games = 0; games < 10; games++)
{
do
{
System.out.print (x + " + " + y + " = ");
guess = s.nextInt();
if (guess != sum && tries < 2)
{
System.out.println("Not quite. Try again!");
System.out.println();
tries++;
}
else
System.out.println("Not quite. The answer is " +sum+ ".");
System.out.println();
}
while (guess != sum);
System.out.println("Congratulations. You got it!");
System.out.println();
}
}}
I'm having trouble with this loop. I cannot get the loop to terminate when I want it to. It's supposed to last for only ten "guesses". In addition, when the user gets the question right, my else statement is also executed. The other thing is that once the user gets the question correct, or does not get the question correct in the three times it is allowed, a new set of numbers are supposed to appear. I have not been able to get that to execute properly either. I've tried different things that worked well, but the requirement for the project is to use a do while loop.
How about something like this?
do {
//your code here
} while (guess != sum && tries <= 10);
The loop will keep going until the sum is correct or the number of tries is exhausted. Increment tries by one every time the loop iterates.
Then, after completion (i.e. outside the loop), do a check to see if the guess is the correct sum or if the tries were exhausted and print out the response accordingly.
Alternatively you can use the break keyword when the guess is correct or no more tries. Also, you should probably reset your tries variable inside the outer for loop (so that it get's reset at the beginning f each game).

Categories

Resources