How to execute a block of code without bypassing another one? Java - java

The title is probably not very informative. But here's the deal.
I want the user to execute a code if it's the second time he is passing there. What I did, was making a if statement, but now I've noticed, that with that, the rest isn't being executed.
Scanner input = new Scanner(System.in);
Random dice = new Random();
int counter = 1;
boolean playing = true;
boolean firstTimmer = true;
boolean got = true;
System.out.println("Welcome to numberMind! From 0 to x, you'll try to guess the random number!");
System.out.println("To quit, guess \"-1\".");
System.out.print("Insert x: ");
int x = 1+input.nextInt();
int objective = dice.nextInt(x);
System.out.print("Ok, I'm ready! What's your first guess? ");
int guess = input.nextInt();
while (playing){
if (guess == -1){
playing = false;
break;
}else if (!firstTimmer){
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1){
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
}else if(guess == 2){
System.out.println("Let's go then!");
}else{
System.out.print("I didn't ask for that number did I? x won't change.");
}
}else{
while(got){
if (objective == guess){
firstTimmer = false;
System.out.println("You guessed it in "+counter+" times!");
counter = 1;
System.out.print("Do you want to paly again? Yes(1) No(2) ");
guess = input.nextInt();
if (guess == 1){
System.out.println("Great! Here we go...");
got = false;
break;
}else if (guess == 2){
System.out.print("Thanks for playing!");
got = false;
playing = false;
}else{
System.out.println("We didn't ask for that. NOW YOU PLAY SOME MORE!");
got = false;
break;
}
break;
}else if (guess == -1){
System.out.println("You quited :(");
break;
}else if (guess == -2){
System.out.println("The correct answer is "+ objective);
}else if (counter >= 5 && (counter -5) % 3 == 0 ){
if (objective % 2 == 0){
System.out.println("The number is pair.");
}else{
System.out.println("The number is odd.");
}
}
System.out.println("You have tryed " + counter++ + " times.");
System.out.print("What's your guess? ");
guess = input.nextInt();
}
}
}
The code I want to run is after the last else. I'm not seeing anything to solve it. Thank you

Well start by asking yourself when the else will be fulfilled: when guess != -1 and firstTimmer == true. You don't ever set firstTimmer, which needs to be set to true to pass through the the else block. You also need to remove the break in your else if, otherwise it will never reach the else on the next iteration.
Also, having both playing = false and break in your if statement is redundant. Both will do the same thing individually.
while (playing){
if (guess == -1){
playing = false;
break;
}else if (!firstTimmer){
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1){
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
}else if(guess == 2){
System.out.println("Let's go then!");
}else{
System.out.print("I didn't ask for that number, x won't change.");
}
firstTimmer = true;
//break;
}else{

int counter = 0;
while(playing) {
counter++; //First iteration: was zero, now 1
if(counter == 2) {
//Do some special thing
}
}

(One) standard pattern for this sort of thing is:
boolean firstTime = true;
boolean playing = true;
int guess = 0;
while (playing) {
if (guess == -1) {
playing = false;
// NOTE: break is redundant with playing flag, here
} else if (!firstTime) {
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1) {
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
} else if(guess == 2) {
System.out.println("Let's go then!");
} else {
System.out.print("I didn't ask for that number, x won't change.");
}
firstTime = false;
} else {
//... do other work here.
}
}
Also, the pattern mentioned by aliteralmind is a more flexible version of the above, allowing you to present a different option for every "visit" through the loop. I can describe further if necessary, with a complete example.

You should try to solve a one problem per time in your code.
Now you have a lot of complicated code that is hard to read and work with.
The answer to your question, regarding the first time visit. Just move it before loop and then start the loop if necessary.
Try to divide the problem in sub programs (methods) and the solve them by once.
displayWelcomeScreen();
preapreGameContext();
do {
if(doUserWantToChange()) {
changeTheGameContext();
}
int gues = askForGues();
hasUserGuesCorrectly();
} while(isTheGameOn());
The final code should look more alike the example above.

Related

Basic Java HiLow guessing game

I am fully aware this question has been asked many times, it is a classic first year problem in CSC. I am not looking for the solution to the problem itself. I think I have it basically done however I am missing something that I cannot find how to do.
Here is my code:
import java.util.Scanner;
import java.util.Random;
public class HiLow
{
public static void main (String[] args)
{
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int num1,guess;
int count = 0;
num1 = generator.nextInt(100) + 1;
while(true) {
System.out.print("Enter an integer between 1 or 100 or enter 0 at anytime to quit: ");
guess = scan.nextInt();
count++;
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
break;
}
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
break;
}
else if (guess > 100 || guess < 1) {
System.out.print("I see you cannot follow instructions. I said ");
count--;
}
else if (guess > num1) {
System.out.println("You have guessed too high. ");
}
else {
System.out.println("You have guessed too low.");
}
}
}
}
My problem is i am required to prompt the user at the point of "if the user quits or successfully guesses the correct number, prompt the user to see if they wish to play again". I am lost and not sure how to continue my while loop from the beginning after my breaks. Is there a way to end the break condition i have from (guess == num1 || guess ==0) and direct my program to start again at the while(true) statement?
Thanks
I will say search up continue;
Tips to help further:
The continue statement is used to bring the loop back to the start, try it instead of a break where you want the user to continue.
You need some sort of check if the user wants to continue, (try asking them to type in some specific int you check, p.s negative numbers are integers as well)
#Ahmed thinks you should continue, I would rather not break, or conditionally break.
Well there are multiple ways you could accomplish this, One would be to just to prompt the user with a "press q to quit" dialogue using the Scanner class where .next() returns the String when the user hits enter:
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
}else{
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
}
System.out.println("would you like to play again [y/n]?");
if(scan.next().equals("y")){
num1 = generator.nextInt(100) + 1;
count=0;
}else{
break;
}
}
If thats what you mean. Hopefully I helped.
or maybe you can have it only quit at zero, if so just remove that second break and replace it with num1 = generator.nextInt(100) + 1; to set the new value to guess.

How to generate a random number after user guess the correct number?

I have written the code below. I have run the program and it allows the user to guess the correct number and return the message successfully. However, I couldn't get it to regenerate a new random number? I also couldn't include an option to ask whether the user wants to quit or not. Please help. Thank you.
import java.util.*;
class CompterAge {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
boolean correctGuess = false;
Random r = new Random();
int randNum = r.nextInt(100-1+1) + 1;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input == "Yes") {
correctGuess = false;
} else {
break;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
}
This code works, I have added another flag variable and corrected some logical errors. See the comments.
boolean correctGuess = false;
boolean endGame = false;
Random r = new Random();
while (!endGame){
int randNum = r.nextInt(101); //Why did you have (100-1+1) + 1 ?? Simple (101) was enough
correctGuess = false;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
correctGuess = true; //Will exit the Inner Loop
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next().toLowerCase();
if (input.equals("yes")) { //You can not use == for String Comparisons
endGame = false;
} else {
endGame = true;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
Your random number generation is done outside of your while loop so when they input that they want to continue the game it should then generate a new number:
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input.equals("Yes")) {
randNum = r.nextInt(100-1+1) + 1;
correctGuess = false;
} else {
break;
}

How do I include a question asking the user if they want to play again?

I am still new to Java and as such I am still figuring some things out. I have been having issues with including code asking the user if they want to play again. I have attempted putting it in the main class in a print statement which gave me an error. After that, I attempted putting it in the Guess.java class in multpile places but I just recieved errors. I have read up on the issue and some sites have suggested a while loop but I am unsure how to implement it into my current code. I have included both the main class which is called GuessingGame.java and the Guess.java class below. Thank you for any assistance that can be provided.
GuessingGame.java
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while (!win) {
System.out.println("You are limited to ten attempts."
+ " Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number"
+ " was: " + answer);
System.out.println("Do you want to play again?: ");
return;
}
if (guess > 1000) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount - 1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount - 1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " + answer);
System.out.println("It took you " + tries + " tries");
}
}
You already found a good position for adding this functionality:
System.out.println("Do you want to play again?: ");
The first step now is to also tell the user what he/she should enter after that question:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
After that we need to get the user input of course:
int number;
//If the user enters e.g. a string instead of a number, the InputMismatchException
//will be thrown and the catch-block will be executed
try {
number = input.nextInt();
//If number < 0 OR number > 1
if(number < 0 || number > 1) {
//The rest of the try-block will not be executed.
//Instead, the following catch-block will be executed.
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
//Clears the scanner to wait for the next number
//This is needed if the user enters a string instead of a number
input.nextLine();
}
If you don't know about try-catch-statements yet, I suggest to read this explanation. For details about the InputMismatchException, please see the documentation.
The problem now is that the user only has one chance to enter 0 or 1. If the user makes a wrong input the program will just stop. One solution to this problem is to just put the code in a while-loop:
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
After this block, we can be sure that number is either 0 or 1. So now we can add a simple if-statement to check the value:
if(number == 0) {
new Guess().doGuess();
}
return;
So all in all the code looks like this:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
if(number == 0) {
new Guess().doGuess();
}
return;
Don't forget to add the following import-statements:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
Try this. Basically, if the user responds with "yes" , we will call the function again.
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number" + " was: " + answer);
System.out.println("Do you want to play again? (yes/no): "); // modified line
if("yes".equalsIgnoreCase(input.next())){ // newly added if block
answer = generateRandomNumber();
tries=0;
i=0;
win = false;
doGuess();
}
return;
}

If else statement

Lately , i have been practicing on my beginner tutorials on java,
However i got stuck with the if else statement ,
My main focus was to let user to write if user try greater than 5 times, it will return false , Else it will return true.
Any help will be greatly appreciated.
int userTry = 0;
double value1 = 0;
Scanner useranswer1 =new Scanner(System.in);
if(userTry == 5){
do{
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
}
while(value1 != 2.5);
System.out.println("You got the right answer");
} else {
} System.out.println("You have zero more tries");
}
Try the following:
int userTry = 0;
double value1 = 0;
Scanner useranswer1 =new Scanner(System.in);
for (int userTry = 5; userTry > 0; userTry--)
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
if (value1 == 2.5) break;
System.out.println(); // empty line
}
if (value1 == 2.5) {
System.out.println("You got the right answer");
} else {
System.out.println("You have zero more tries");
}
}
The key is to set the condition of your do-while loop based on the check that the user didn't get the right value and if they have enough retries.
If the user got the right value, they've done so in the required number of retries, otherwise, they've zero tries. Hope this helps.
int userTry = 0;
double value1 = 0.0;
Scanner useranswer1 = new Scanner(System.in);
do {
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
} while (value != 2.5 && ++userTry < 5); // NOTE: pre-increment and check. If you like to have a safer version, move this increment inside the while loop.
if (value1 != 2.5) {
System.out.println("You have zero more tries");
} else {
System.out.println("You got the right answer!");
}
int count = 0;
double trueAnwer = 6.66;
while (true) {
count++;
Scanner useranswer1 =new Scanner(System.in);
if (trueAnwer == useranswer1.nextDouble()) {
System.out.println("You got the right answer");
return;
}
if (count==5) {
System.out.println("You have zero more tries");
return;
}
System.out.println("This is "+count+" times");
}
Try this:
do{
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
userTry++;
}
while(value1 != 2.5 && userTry != 5);
if(userTry == 5){
System.out.println("You have zero more tries");
} else {
System.out.println("You got the right answer");
}

New Java developer - Simple Q

I have just recently started coding and am quite the beginner. I'm trying to make a program that simply asks the user to enter a "password", and depending on whether the password is correct; increment a counter. And, once the counter reaches 10, print out a message.
Basically what I'm trying to make is like a "clip-card", like one of those you can get at a coffee shop (you get every 10th coffee free).
So, this is what I have now. I just need to know how to make the program continue after inputting a password, and keep track of the inputs.
Ohhh and... If this is unclear, please say so and I will try to clarify.
This is what I have to far...
import java.util.Scanner;
public class Coffee {
public static void main(String [] args){
int count = 0;
String pass = "hey";
System.out.println("Enter password: ");
Scanner key = new Scanner(System.in);
String moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
}
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
}
if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
When would your program end? The way you describe it, it could just go on forever.
If that is the case, you just enclose it in a while loop :
public static void main(String [] args) {
Scanner key;
String moves;
int count = 0;
String pass = "hey";
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
}
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
}
if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
But you really should have an breaking condition.
You need loop(while,do-while,or for loop) to do this kind of repeated stuff .
Sample code may help
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
int count = 0;
String pass = "hey";
System.out.println("Enter password: ");
Scanner key = new Scanner(System.in);
String moves = key.nextLine();
boolean flag = true;
while (flag) {
if (moves.compareTo(pass) == 0) {
count++;
System.out
.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
}
if (count == 10 && count != 0) {
System.out.println("You've got a free coffe!");
count=0;
}
if (moves.compareTo(pass) != 0) {
System.out.println("Wrong password! Try again.\n");
}
System.out.println("Do you want to continue ..(y/n)");
String choice = key.nextLine();
if (choice.equals("n")) {
flag = false;
} else {
flag = true;
}
}
}
}
I will give you a while and do-while loop to chose from
While loop
Scanner key;
String moves;
int count = 0;
String pass = "hey";
boolean condition=true;
while(condition) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
condition=false;
}
}
else if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
Do-While loop
Scanner key;
String moves;
int count = 0;
String pass = "hey";
boolean condition=true;
do{
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
condition=false;
}
}
else if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}while(condition);

Categories

Resources