I am having trouble implementing a "while" loop in Java [duplicate] - java

This question already has answers here:
How is if/while condition evaluated when we use assignments instead of comparison?
(4 answers)
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
This is my code.
import java.util.Scanner;
public class passwordProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String correctPassword = "WooHoo";
int tries = 0;
boolean keepGoing = true;
while(keepGoing = true) {
tries = tries + 1;
System.out.println("try #" + tries);
String password;
System.out.println("Please enter the password: ");
password = scan.next();
if(password == correctPassword) {
System.out.println("This is the correct result:" + password);
keepGoing = false;
if(tries >= 3) {
System.out.println("Too many wrong tries. Exiting program");
keepGoing = false;
break;
}
}
}
}
}
The while loop doesn't end when the right password is entered, and it keeps repeating after the allowed number of attempts has been reached and I want to know why.
Is it because of the condition statement in the while loop or is there something else wrong with the code?

while (keepGoing = true)
this doesn't verify whether keepGoing is true, it sets it to true, so it remains true.
You should change it to:
while (keepGoing == true)
or, shorter:
while (keepGoing)
EDIT:
Another problem you have, is the way you compare your String values.
if(password == correctPassword)
The == operator is used to compare references of Objects, or primitive values, not the values of Objects.
What you want here, is:
if ( correctPassword.equals(password))
Here's a good read about that:
How do I compare strings in Java?
EDIT 2:
Your conditional statements shouldn't be nested. If they are, that means the second one will only execute if the first one evaluates to true:
if(correctPassword.equals(password)) { // already corrected
System.out.println("This is the correct result:" + password);
keepGoing = false;
if(tries >= 3) {
System.out.println("Too many wrong tries. Exiting program");
keepGoing = false;
break;
}
}
should be rewritten as:
if(correctPassword.equals(password)) { // already corrected
System.out.println("This is the correct result:" + password);
keepGoing = false;
}
if(tries >= 3) {
System.out.println("Too many wrong tries. Exiting program");
keepGoing = false;
break;
}

Your condition is an assignment, not a check.
Try changing it to while(keepGoing==true).

The '=' operator sets a value to a variable. The '==' operator compares values. A good practice it would be to just write the following statement:
while(keepGoing) {
...
}
You can just parse a boolean inside the 'while' statement and it will go on while the boolean is true.

In order to check a condition you should use "==" instead of "=" so the while statement should look like this:
while(keepGoing == true) {
...
}

Related

How to fix variable might not have been initialized [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 3 years ago.
I am trying to create a method that spits out a boolean value if the user enter 1 word that is included in a list of 6. otherwise prompt the user until he enters 1 corrected one
I've tried using a while loop with switch but it doesnt seem to work
/**
* If the user says yes or y or true, return boolean value of true
* if the user says no or n or false, return boolean value of false
* Display a prompt if user fails to write any of 6 above words until
* the user does
*/
public static boolean promptForYesNo(Scanner in, String prompt){
boolean toReturn;
boolean valid;
String userAnswer;
System.out.println(prompt + "Yes or No?");
userAnswer = in.next();
userAnswer = userAnswer.toLowerCase();
while (userAnswer.equals("yes") || userAnswer.equals("y") ||
userAnswer.equals("true") ||userAnswer.equals("no") ||
userAnswer.equals("n") || userAnswer.equals("false")){
if (userAnswer.equals("yes") || userAnswer.equals("y") ||
userAnswer.equals("true")){
toReturn = true;
}
else if(userAnswer.equals("no") || userAnswer.equals("n") ||
userAnswer.equals("false")){
toReturn = false;
}
else {
System.out.println(prompt + "Yes or No?");
userAnswer = in.next();
userAnswer = userAnswer.toLowerCase();
}
}
return toReturn;
}
Even if you initialize the variable, it won't satisfy your intention. Instead, you should recursively call the method again with the arguments until you expect the user's intention, like so:
public static boolean promptForYesNo(Scanner in, String prompt){
System.out.println(prompt + "Yes or No?");
String userAnswer = in.next();
userAnswer = userAnswer.toLowerCase();
if (userAnswer.equals("yes") || userAnswer.equals("y") ||
userAnswer.equals("true")){
return true;
}
else if(userAnswer.equals("no") || userAnswer.equals("n") ||
userAnswer.equals("false")){
return false;
}
else {
return promptForYesNo(in, prompt);
}
}
I have cleaned up your code a bit.
The above code goes in continuous loop: use break when condition is satisfied
while (conditions) {
if (conditions) {
toReturn = true;
break;
} else if (conditions) {
toReturn = false;
break;
} else {
System.out.println(prompt + "Yes or No?");
userAnswer = in.next();
userAnswer = userAnswer.toLowerCase();
}
}

Loop certain IF statements in java

import java.util.Scanner;
public class main {
public static void main(String[] args) {
int number = 0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of sides");
number = input.nextInt();
if (number == 1) {
System.out.println("Circle");
}
if (number == 3) {
System.out.println("Triangle");
}
if (number == 4) {
System.out.println("quadrilateral");
}
else {
System.out.println("Incorrect Input");
}
}
}
Hello, I am trying to use the if statement. Can anyone advise me how to loop if statements? Because I get this as a result for example:
circle
Incorrect Input.
Also, How could I repeat the scanner so it allowed me to type another input?
Currently, the else clause is only associated to the last if block i.e. if (number == 4) {...} This means if any of the other if blocks are executed, it will still print "Incorrect Input". The solution is to use else if instead of separate if's.
if (number == 1) {
System.out.println("Circle");
}else if (number == 3) {
System.out.println("Triangle");
}else if (number == 4) {
System.out.println("quadrilateral");
}
else {
System.out.println("Incorrect Input");
}
You can use switch case (see : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html).
And you can check the type of number or string with instanceof.
For your second part question, I guess you're looking for something like a do....while loop, you can set up some condition like if the input result is not a number, then it will stuck in the loop until the user type in a number then only go in the the if, else-if statement

Java do while loop with multiple conditions not executing properly

I have to write a Magic 8 ball program that will account for user input errors and I have to use a loop to do that.
boolean okay;
do {
System.out.printf("What is your question?\n");
questionStr = keyboard.nextLine();
int length = questionStr.length();
if (questionStr.length() == 0) {
System.out.println("Not allowed.");
okay = false;
} else if (!(questionStr.charAt(length - 1) == '?')) {
System.out.println("Add question mark.");
okay = false;
} else if (questionStr.length() > 60) {
okay = false;
}
okay = true;
} while (!okay);
When I run the code and make it an empty string, it does print out not allowed however it still runs the rest of the code and does not loop back and ask "What is your question?" The same happens with the question mark; it prints out "Add question mark" but does not loop back like it is supposed to. If I make a question longer than 60 characters, the code still executes and does not loop back and continue asking the user "What is your question?" until the code is less than 60 characters. I am trying to figure out what I am doing wrong here.
Move okay = true; before your if statements that negate it,
okay = true;
if (questionStr.length() == 0) {
System.out.println("Not allowed.");
okay = false;
} else if (!(questionStr.charAt(length - 1) == '?')) {
System.out.println("Add question mark.");
okay = false;
} else if (questionStr.length() > 60) {
okay = false;
}
As posted, you unconditionally set okay to true before your condition while (!okay); and thus the loop always ends.

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

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.

Printing a statement only once in a while loop

This is probably very simple, however I have completely blanked and would appreciate some pointers. I'm creating a small game we have been assigned where we select numbers and are then provided a target number to try and reach using the numbers we selected. Inside my while loop once my condition hits 6 it asks the user to generate the target number, however once they do it prints the same string again "Generate the final string" how do I print this only once?
Here is the code if it will help.
while (lettersSelected == false) {
if (finalNum.size() == 6) {
System.out.println("3. Press 3 to generate target number!");
} // Only want to print this part once so it does not appear again.
Scanner input = new Scanner(System.in);
choice = input.nextInt();
switch (choice) {
case 1:
if (finalNum.size() != 6) {
largeNum = large.get(r.nextInt(large.size()));
finalNum.add(largeNum);
largeCount++;
System.out.println("Numbers board: " + finalNum + "\n");
}
break;
It can be done very easily.
boolean isItPrinted = false;
while (lettersSelected == false) {
if ((finalNum.size() == 6) && (isItPrinted == false)) {
System.out.println("3. Press 3 to generate target number!");
isItPrinted = true;
}
The condition if (finalNum.size() == 6) is satisfied first and so the string is printed. However, during the next iteration of the while loop, the size of finalNum has not changed as the contrary of the condition is checked in the case 1 of the switch and the size is not changed anywhere between these two statements.
You can add a flag variable and set it to true, add a check for that variable in the if contidion and if the if-clause is entered, set the variable to false:
boolean flag = true;
while (lettersSelected == false) {
if (finalNum.size() == 6 && flag) {
System.out.println("3. Press 3 to generate target number!");
flag = false;
}
// ...
}

Categories