(JAVA) Break command is executing when it shouldn't [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I just started to learn Java, and I'm a bit lost as to why my "break" command at the bottom of the code is being executed.
import java.util.Scanner;
public class GradeValues {
private static Scanner scanner;
public static void main(String[] args) {
boolean keepGoing = true;
String grade; // initializing variable for grade
while(keepGoing = true){
System.out.println("What percentage did you get? "); //Ask User the question
scanner = new Scanner(System.in); //starting the scanner
grade = scanner.nextLine(); //storing user input of percentage
int percentage = Integer.parseInt(grade); //converting string to a int
if(percentage >= 80 && percentage <= 100){
System.out.println("Your grade is an A! Awesome job!");
}else if(percentage >= 70 && percentage <= 79){
System.out.println("Your grade is an B! Nice work!");
}else if(percentage >= 60 && percentage <= 69){
System.out.println("Your grade is an C! That's average. =( ");
}else if(percentage >= 50 && percentage <= 59){
System.out.println("Your grade is an D! Come on man, you can do better.");
}else if(percentage < 50){
System.out.println("Your grade is an F! You need to hit the books again and try again.");
}else{
System.out.println("I think you type the wrong value.");
}
System.out.println("Would you like to check another grade?"); //Asking user if they want to do it again
Scanner choice = new Scanner(System.in); //Gets user input
String answer = choice.nextLine(); // Stores input in variable "answer"
if(answer == "yes"){
keepGoing = true; //While loop should keep going
}else{
keepGoing = false; //While loop should stop
break; //this should stop program
}
}
}
}
Considering that the keepGoing boolean variable is still true (if the user types 'yes'), the application will still stop because of the break in the else statement. Can someone let me know why it's doing that and how to fix that?

You cannot compare string with == operator.
In order to compare the strings correctly you have to use equals method.
For example replacing in your code the if/else statement with:
if("yes".equals(answer)){
keepGoing = true; //While loop should keep going
}else{
keepGoing = false; //While loop should stop
break; //this should stop program
}

I guess if its not typo then your while condition is not correct while(keepGoing = true) ... should be while(keepGoing == true) or while(keepGoing). And with that you don't need to break at end. And like suggested in other answers please use equals to compare strings.

answer is a String, which is a type of object. You should compare it with the equals method, not the == operator:
if (answer.equals("yes")) {
// etc.

Related

Substract 1 after each loop end [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 2 years ago.
Improve this question
I'm new at java and i tried to make a Guess The Number game.
When the loop starts, i want to check if the user has any tries left.
if (remain > 1);
then after each end of the loop I want to subtract 1 from the tries.
I also tried to gather 1 after each loop ends.
byte tries = 5, remain=(byte)(--tries);
When user is out of tries i want to break the loop and break the game:
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
Here's my code:
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte tries = 5, remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1);
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
Code works perfectly but it won't break when user is out of tries.
tries variable should be initialized outside the while loop and the if statement was being closed using a ';'
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
byte tries = 5; // tries should be initialized outside the loop
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1) { // You were using ; and this if statement was closed
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
I think you are misunderstanding a lot of concepts. Here's a commented version :
public class Master {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// The number to found
double numberToFound = (byte)(Math.random() * 21);
// The user number will be stored here
byte userInput = 0;
// The number of tries left
byte tryLeft = (byte) 5;
do {
// Ask the User an number
System.out.print("Choose a number between 1 and 21 :");
userInput = scanner.nextByte(); // Store it
// Test the number
if (userInput > numberToFound) {
System.out.println("You are lower than the number!");
} else {
System.out.println("You are higher than the number!");
}
tryLeft--; // We remove one try
} while(tryLeft > 0 && userInput != numberToFound); // We loop until there are no more try OR we found the number
// Last time check (we check why we exited the loop)
// The user found the number
if (numberToFound == userInput)
System.out.println("You have guessed the number!");
else // The user has no more tries left
System.out.println("You haven't guessed the number!");
}
}
You should avoid using while(true) if you have a breaking condition for better readability.
You can try this code.
I changed some datatypes and added the decreasing of the remain variable inside the loop.
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int number = (int)(Math.random() * 21);
int tries = 5;
int remain = tries;
while(true){
System.out.print("Choose a number between 1 and 21:");
int user = scanner.nextInt();
// User input
System.out.println(remain);
if (remain > 1) {
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
--remain;
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
First of all, you can check if the "remain" is bigger than 0 and not 1, and your code will do the job as you planned (and you don't need to check == 0 at the else) :)
Second of all small comments to make your code more arranged:
Work with parameters that are comfortable to you like int (easier to debug and work with) you should use byte only if the code really needs it.
Move parameters that you use only to check them outside the loop like tries (think on that you will define this variable on every loop iteration and you don't need to).
Add to the params you are not going to change (like tries & number after you moved outside the loop) final it will be more clear that you are not going to change this param anymore.
Other than that looks great, good luck! :)

How to restart while loop in Number Guessing Game

I'm having a problem with this code.
The issue as I see it is that when the user runs the code and either guesses correctly or uses the max number of attempts, the while loop doesn't kick in and allow the game to restart.
My idea is to reset the counter (attempt) to zero and start again but I'm just getting the exit message with the overall score instead.
int guess = 0;
int attempt = 0;
int number = new Random().nextInt(1000) + 1;
int scorePlayer = 0; int scoreComputer = 0;
boolean repeat;
System.out.println("Hello and welcome to the number guessing game.");
System.out.println("Please guess a number between 1 and 1000");
while(repeat == true){
do{
Scanner scan = new Scanner(System.in);
guess = Integer.parseInt(scan.nextLine());
System.out.println("The number you guessed is "+guess);
attempt++;
if(guess == number){
System.out.println("Congratulations! You got it!!");
scorePlayer++;
System.out.println("Would you like to play again? [YES/NO]");
Scanner a = new Scanner(System.in);
String answer = a.nextLine().toUpperCase();
if (answer != "YES"){
//repeat = false;
System.out.println("Thank you for playing");
System.out.println("The final score is "+scorePlayer+" to you and "+scoreComputer+" to the server");
if (scorePlayer<scoreComputer){
System.out.println("Computer wins!");
}else{
System.out.println("You win!");
}break;
}else{
attempt = 0;
}
}else if(guess < number){
System.out.println("That is incorrect, try a larger number");
}else if(guess > number){
System.out.println("That is incorrect, try a smaller number");
}if(attempt == 10 && guess != number){
System.out.println("That is the max number of guesses allowed");
System.out.println("The number you were looking for is "+number);
scoreComputer++;
System.out.println("Would you like to play again? [YES/NO]");
Scanner b = new Scanner(System.in);
String answer = b.nextLine().toUpperCase();
if (answer != "YES"){
//repeat = false;
System.out.println("Thank you for playing");
System.out.println("The final score is "+scorePlayer+" to you and "+scoreComputer+" to the server");
if (scorePlayer<scoreComputer){
System.out.println("Computer wins!");
}else{
System.out.println("You win!");
}break;
}else{
attempt = 0;
}
}
}while(guess != number || attempt == 0);
repeat = false;
}
Single "=" is an assignment operator, simply change it to the double "==".
while(repeat == true)
In addition to what ugur said, you can simply do
while(repeat)
because repeat is a boolean variable (returning true or false)
Check the last line in the outer loop you are setting repeat=false. So when you break from the inner loop, outer while check for repeat and it is false every time except the first.

Can't seem to repeat my low-high game

I am trying to develop a simple high low game that asks the user after playing if they would like to play again. If I remove the outer while loop the logic of the inner loop does exactly what I want it to do, however I am unsure how to wrap the inner loop with an outer loop that will ask the play again question and if the answer is yes put them back into the inner loop. Below is my code.
import java.util.Scanner;
import java.util.Random;
public class HiLoGuess {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100)+1; // Generates a random number for the game.
int count = 0; // Placeholder for the guess counter.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
String newgame = "y";
while (newgame.equalsIgnoreCase("y"))
{
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{
System.out.println ("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0 )
{
System.out.println("Your guess is too low, guess again");
}
else if (guess > answer)
{
System.out.println ("Your guess is to high, guess again");
}
else if (guess == answer)
{
System.out.println ();
System.out.println ("You guessed correctly, you win!!!");
System.out.println ("It took you " + count + " guesses");
}
}
System.out.print();
System.out.println("Play another game: y or n?");
newgame = scan.nextLine();
}
}
}
You need to put these initializations into the outer loop:
int guess = -1;
int answer = numb.nextInt(100)+1;
int count = 0;
Otherwise they keep the value from the last game and the inner loop will not be executed any more.
you never reset your guess, sentinel, or answer variables
so (guess != sentinel && guess != answer) always evaluates to false after the first time the game is played, and therefore the inner while loop never executes after the first game
while (guess != sentinel && guess != answer) //this is false after the first game because you don't reset variables
{ ...}
Update for OP comment:
to get your code to do what you want you need to add the resets between the outter and inner while loop like this
while (newgame.equalsIgnoreCase("y"))
{
guess = -1;
answer = numb.nextInt(100)+1;
count = 0;
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{ ...}
}
Replace newgame = scan.nextLine(); by this : newgame = scan.next();
And you need to initialise your variables inside your while loop, so that the flag is reseted to false and the random generate new result to guess.
public class Game
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
String newgame = "y";
while (newgame.equalsIgnoreCase("y")) {
int count = 0; // Placeholder for the guess counter.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100) + 1; // Generates a random number for the game.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
while (guess != sentinel && guess != answer) // Loop that ends when user enters a zero.
{
System.out.println("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0) {
System.out.println("Your guess is too low, guess again");
} else if (guess > answer) {
System.out.println("Your guess is to high, guess again");
}
else if (guess == answer) {
System.out.println();
System.out.println("You guessed correctly, you win!!!");
System.out.println("It took you " + count + " guesses");
}
}
System.out.println();
System.out.println("Play another game: y or n?");
newgame = scan.next();
}
}
}

Can I use "return" in here or any ideas?

I'm really new to Java and most of my knowledge are self- taught. can you help me to figure out this.
Our teacher wants us to make a menu about Java. Where the output something like this..
Menu
1 - Java History
2- Java Keywords
3 - Java Arrays and so on. .
Do you want to read one (Yes/No):
//if yes
Please enter a menu number:
// then it will display an information..
//my problem is that how can I connect the new entered value to the first method so that I don't have write it all over again...
this is whats on my mind..
but im stuck..
import java.util.Scanner;
public class Program {
public static void main (String [] args) {
System.out.println("Please enter a number:");
int x = nextInt();
if (x == 1) {
for (int x = 5; x == 5;x++) // array of 1(first menu)
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
}
else if (x == 2) {
for loop of array 2
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
}
else if (x == 3) {
for loop of array 3
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
else if (x ==4) {
for loop of array 4
else if (x == 5) {
for loop of array 5
else if (x == 6) {
for loop of array 6
else if (x == 7) {
for loop of array 7
else if (x == 8) {
for loop of array 8
else if (x == 9) {
for loop of array 9
else if (x == 10) {
for loop of array 10
else {
//exit the program
If I understand correctly, you would want to implement the While or do while statement in your program.
Example of While and Do While Loops
Im not really sure what you are trying to accomplish with your program but here is a little example I made quickly of how to utilize the for loop in your case. `import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean keepGoing = true; //As long as this is true the while statement will continue;
while (keepGoing) {
System.out.println("Enter a number");
int x = scan.nextInt();
//logic
if (x == 1) {
System.out.println("X is equal to 1");
} else if (x == 2)
System.out.println("X is equal to 2");
//prompts the user if they want to keep going.
System.out.println("Would you like to keep going? Y/N");
String decision = scan.next();
if (decision.equalsIgnoreCase("y")) {
keepGoing = true;
} else {
System.out.println("Quitting...");
keepGoing = false;
}
}
}
}
`

How to stop the method continuously looping

I am currently trying to complete a program with multiple classes in java that will allow the user to input information to help him or her book tickets, accommodation, parking, etc for a rock festival. I have started with one of the classes 'accommodation' to return the correct input of the user to the main class, however, I have found when I run the program and enter option 3, it immediately loops continuously which I have to terminate. I have searched online for a way to stop the loop, and for it to return the correct inputted information to no avail, I would appreciate any help to a very new new noob, before this loop turns me loopy!
Below is my main class and the class 'accommodation'. thank you in advance and apologies for any messy coding I have, as I have been trying various options as I have said before.
import java.util.Scanner;
import java.util.InputMismatchException;
public class clydeRockfest {
public static void main(String[] args) {
boolean quit = false;
Scanner in = new Scanner(System.in);
int choice; // Display the menu
int answer = 0;
Accommodation accommodation = new Accommodation();
//accommodation.getaccommodation();
do{
System.out.println("1\t Festgoers");
System.out.println("2\t Ticket");
System.out.println("3\t Accommodation");
System.out.println("4\t Transport");
System.out.println("5\t Parking");
System.out.println("0\t Quit");
System.out.println("Please enter your choice:");
//Get user's choice
choice=in.nextInt();
if(choice == 0)
quit=true;
//Display the title of the chosen module
switch (choice) {
break;
case 3: accommodation.getaccommodation();
System.out.println("You require " + answer + " accommodation.");
break;
case 0:
quit=true;
break;
default: System.out.println("Invalid choice, please choose again.");
} //end of switch
} //end of the main method
while(!quit);
} //end of class
}
public class Accommodation {
private String accommodation;
void getaccommodation(){
int no = 0; // no accommodation at all required
int self_Pitch = 0; // chosen if requiring a pitch
int tent = 0; // chosen if using a tent
int answer = 0;
int choice = 0;
boolean done = false;
System.out.println("Do you require accommodation?");
System.out.println();
// Answer validation loop
boolean validanswer = true;
while (!validanswer){
System.out.println("Enter:(1=NO, 2=SELF-PITCH, 3=TENT)");
System.out.println();
if(answer > 0 && answer < 4){
validanswer = true;
done = true;
}// ends if
else{
System.out.println();
System.out.println("That is not a valid answer, please choose again:");
System.out.println();
} // ends else
} //ends while
}
public void setaccommodation(String accommodation){
this.accommodation = accommodation;
}
Output:
Please enter your choice:
3
Do you require accommodation?
You require 0 accommodation.
1 Festgoers
2 Ticket
3 Accommodation
4 Transport
5 Parking
0 Quit
Please enter your choice:
you prime your loop by setting done=false but never set done = true so your loop will never end
You have two loops checking if user is done, and the condition of the first one (with the done) variable is never changed. Just remove this loop, and you should be fine.
Also, it looks like the condition for the second loop variable should be
if (answer > 0 && answer < 4)
to match your menu alternatives.
You never set done to true. It seems you may need to do it here:
if(answer >=0 && answer <=4){
validanswer = true;
done = true;
}
else{
//code
}
However, I'm not even sure you need that outer loop in the first place:
while(!done){
It seems redundant.

Categories