How to repeat if statements in while loops [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to have a user guess a number picked by a random number generator, but my code decides to, if it doesn't equal, stick within one if statement.
System.out.println("Enter a guess between 1 and 200: ");
String guess = input.nextLine();
int userInput = Integer.parseInt(guess);
Random rnd = new Random(seed);
int x = rnd.nextInt(200) + 1;
int currentInt = 1;
String msg = "That was impossible!";
and my while loop contains many if statements:
boolean boo = false;
while (!boo) {
if (userInput == x) {
System.out.println("Congratulations! Your guess was correct!");
System.out.println("");
System.out.println("I had chosen " + x + " as the target number.");
System.out.println("You guessed it in " + currentInt + " tries.");
if (currentInt == 1) {
//do something
} else if (currentInt >= 2) {
//do something
} else if (currentInt >= 4) {
...
} else if (currentInt >= 11) {
msg = "Maybe you should play something else";
System.out.println(msg);
}
break;
} else if (userInput > x) {
System.out.println("Your guess was too high - try again.");
System.out.println("");
System.out.println("Enter a guess between 1 and 200: ");
String highGuess = input.nextLine();
int tooHigh = Integer.parseInt(highGuess);
continue;
} else if (userInput < x) {
System.out.println("Your guess was too low - try again.");
System.out.println("");
System.out.println("Enter a guess between 1 and 200: ");
String lowGuess = input.nextLine();
int tooLow = Integer.parseInt(lowGuess);
continue;
}
currentInt = currentInt + 1;
}
My code works decently, if the answer is correct in the first try then the first if statement works, but if it's greater or less than x, then the same block runs (if greater, keeps putting greater even if next input is less than)

Update userInput with tooHigh and tooLow .

Related

Problem producing a new random number at the end of HiLo guessing game

I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?
int answer = (int)(Math.random() * 100 + 1);
int guess = 0;
int guessCount = 0;
boolean playGame = true;
String restart;
Scanner scan = new Scanner(System.in);
while(playGame == true)
{
while (playGame == true)
{
System.out.println("Enter a number between 1 and 100: ");
guess = scan.nextInt();
guessCount ++;
System.out.println(answer);
if (guess < 1 || guess > 100)
{
System.out.println("You have entered an invalid number.");
guessCount --;
} else if (guess == answer)
{
System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
break;
} else if (guess > answer)
{
System.out.println("You've guessed too high! Guess again: ");
} else if (guess < answer)
{
System.out.println("You've guessed too low! Guess again: ");
}
}
System.out.println("Would you like to play again? Y/N");
restart = scan.next();
if (restart.equalsIgnoreCase("Y"))
{
playGame = true;
} else if(restart.equalsIgnoreCase("N"))
{
System.out.println("Thank you for playing!");
break;
}
}
The value in the variable 'answer' remains same since variable is a reference to what you have stored / Initialized or Assigned. It does not manipulate in itself. You have to rewrite the code for e.g. answer = (int)(Math.random()*100+1) at the point before game will be restarted or after it.
You're initializing the answer before the loop, it never changes. You have to assign answer a new value when the user chooses to play a new round. This is not the code I'd write, but here it is:
if (restart.equalsIgnoreCase("Y"))
{
answer = (int)(Math.random() * 100 + 1);
}

Java. making a question re-ask if you get it wrong

I am new to java so I'm terrible at it. Basically I am making a multi choice quiz thing.
But my problem is that even if you get the question wrong it goes to the next question
and I want it to ask the same question again, like a loop. I have tried to make it work but I can't, it's probably very simple and easy.
If anyone can help that would be cool !
it says
whats 9+10?
1. 19
2. 21
3. 18
current code:
iAnswer = Integer.parseInt(System.console().readLine());
if (iAnswer == 1) {
System.out.println(" ");
System.out.println("Correct");
}
else {
iLives -= 1;
System.out.println(" ");
System.out.println("Incorrect");
}
(when you get a question wrong you lose a life, but i don't think that matters)
I'm not sure if this is what you asked for but I came up with this !
//get input from console
Scanner scanner = new Scanner(System.in);
//create a loop to keep
while (true) {
//get 2 random number on value(0 - 20)
int n1 = (int) (Math.random() * 20 + 1);
int n2 = (int) (Math.random() * 20 + 1);
//correct Answer is saved in correctAns value
int correctAns = n1 + n2;
System.out.println("What is the anwser of : ");
System.out.print(n1 + " + " + n2 + " = ");
//get the answer from user input
int ans = scanner.nextInt();
//if user input is equal to current Answer
if (ans == correctAns) {
System.out.println("Congrats next question !");
} else {
//if user input is not equal to currentAns
boolean condition = true;
//create another loop where user has to answer right to get to
//the next question
while (condition) {
System.out.println("What is the anwser of : ");
System.out.print(n1 + " + " + n2 + " = ");
ans = scanner.nextInt();
//if user input is equal to currentAns
if (ans == correctAns) {
//stop the loop and continue to the other question
condition = false;
} else {
// if user input is not equal to currentAns keep asking
// the same question
condition = true;
}
}
}
}

java: method correctOutOf in class littleQuiz cannot be applied to given types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My goal is to store the amount of correct answers into the 'correctOutOf' method, which will then return the value of corrAns when called int the /*Wrapping Up*/ section of the example code below:
import java.util.Scanner;
public class littleQuiz {
public static void main(String[] args){
Scanner key = new Scanner(System.in);
char yesno;
int answer;
/*Welcome/Splash Screen*/
/*Ask if ready and accept yes or no with appropriate return response*/
System.out.print("Are you ready for a quiz? Y or N ");
yesno = key.next().charAt(0);
if (yesno == 'Y'){
/*affirmative response*/
System.out.println("Okay, here it comes!");
}
else{
/*negative response*/
System.out.println("What a wimp...");
System.exit(0);
}
/*Quiz Section*/
/*Question 1*/
System.out.println("Q1) What is the capital of Alaska?");
System.out.println(" 1) Melbourne\n" +
" 2) Anchorage\n" +
" 3) Juneau");
answer = key.nextInt();
if (answer == 3){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Question 2*/
System.out.println("Q2) Can you store the value 'cat' in a variable of type int?");
System.out.println(" 1) yes\n" +
" 2) no");
answer = key.nextInt();
if (answer == 2){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Question 3*/
System.out.println("Q3) What is the result of 9+6/3?");
System.out.println(" 1) 5\n" +
" 2) 11\n" +
" 3) 15/3");
answer = key.nextInt();
if (answer == 2){
System.out.println("\nCorrect!!!");
/*store to function stating number of correct answers*/
}
else{
System.out.println("\nWrong.");
}
/*Wrapping Up*/
System.out.println("Overall, you got " + correctOutOf() + " out of 3 correct.");
System.out.println("Thanks for playing!");
}
/*not sure of which access modifier to use, but none have fixed it*/
private static int correctOutOf(int answer) {
return corrAns;
}
}
I'm feeling pretty positive that my if statement is going to feed the 'correctOutOf' method simply because it is the only part of the statement that can check for a correct answer with the code as-is. (just so everyone knows my train of thought.)
Edit - if this is something more than a beginner should be messing with, thanks for pointing it out. (Biting off more than I can chew?)
Don't do that, do this at the start of main:
byte correct = 0;
Or this if you ever need to use it outside of main:
private static byte correct = 0;
Then add this to each correct answer if statement:
correct++;
And print the variable "correct".
...also, you may wish to add this function to your program, to replace "key.nextInt()", to prevent the user from crashing your program:
import java.util.regex.*;
private static final int integer() {
boolean invalid = true;
int number = 0;
while (invalid) {
String input = key.next();
if (input.matches("\\d+")){
invalid = false;
try {
number = Int.parseInt(input);
} catch (java.lang.NumberFormatException e) {
invalid = true;
System.out.print("Are you trying to break the program? Try again: ");
}
} else {
System.out.println("That's not a whole number! ");
System.out.print("Try again: ");
}
}
return number;
}

Figuring out odd even and zeros [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am having problems with my java program. I have to input a value then print out the number of odds, evens, and zeroes. The odds and zeroes display fine but the evens display total digits.
import java.util.Scanner;
public class OddEvenZero
{
public static void main(String[] args)
{
int even = 0;
int odd = 0;
int zero = 0;
int placeInValue;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Value: ");
String valueEntered = scan.nextLine();
for(placeInValue = 0; placeInValue < valueEntered.length(); placeInValue ++)
{
char value = valueEntered.charAt(placeInValue);
int numberUsedInLoop = Integer.parseInt(Character.toString(value));
if(numberUsedInLoop == 0)
{
zero ++;
}
else if(numberUsedInLoop%2 == 0);
{
even ++;
}
if(numberUsedInLoop%2 != 0 && numberUsedInLoop != 0)
{
odd ++;
}
}
System.out.println("Number of Zeroes in Number: " + zero);
System.out.println("Number of Evens in Number: " + even);
System.out.println("Number of Odds in Number: " + odd);
}
}
Output:
Enter a Value:
225500
Number of Zeroes in Number: 2
Number of Evens in Number: 6
Number of Odds in Number: 2
Any help is appreciated.
The semicolon terminates the else if immediately here
else if(numberUsedInLoop%2 == 0); // <-- terminates the else if
{ // <-- raw block
even ++;
}
change it to something like
else if(numberUsedInLoop%2 == 0)
{
even ++;
}
else // <-- just an else should satisfy your conditions
{
odd ++;
}

boolean is assigned but never accessed [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm just trying to create a GuessMyNumber game and here is my code:
import java.util.Random;
import java.util.Scanner;
public class classic {
public static void main(String[] args) {
Random rand = new Random();
boolean beaten = false;
int number;
int randn = rand.nextInt(99);
//System.out.println(randn);
System.out.println("What is my number? Guess it!");
Scanner input = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
while(beaten = true){
number = input.nextInt();
if (number == randn) {
System.out.println("Correct!");
beaten = true;
}
if (number < randn) {
System.out.println(number + " is too low");
}
if (number > randn) {
System.out.println(number + " is too high");
}
}
}
}
In the while loop I set beaten = true but still, while loop continues
What am I doing wrong here?
while(beaten = true)
As = is an assignment operator, so true is assigned into beaten first, then while loop condition becomes,
beaten = true
while(true) {
//.... hence, loop executed.
}
Use comparison operator == for condition checking. Moreover, not ! operation can be used also for boolean variable.
Say,
beaten = true
Then
while(!beaten)
means
while(!true) // read while not true
//implies
while(false) {
//.... loop will not going to execute.
}
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Random rand = new Random();
boolean beaten = false;
int number;
int randn = rand.nextInt(99);
//System.out.println(randn);
System.out.println("What is my number? Guess it!");
Scanner input = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
while(beaten == false ){
number = input.nextInt();
if (number == randn) {
System.out.println("Correct!");
beaten = true;
}
if (number < randn) {
System.out.println(number + " is too low");
counter++;
}
if (number > randn) {
System.out.println(number + " is too high");
counter++;
}
}
System.out.print("It took you " + counter + " tries to gues the number");
}
}
Now it works. You set "beaten" to false originally so it wasn't working and I also changed your while loop condition too "beaten == false" instead of "beaten = false" Hope this helps. I didn't know what you wanted to do with the counter so I just added that into the bottom to count how many tries it took.

Categories