简体   繁体   中英

I'm trying to get the loop to run on the conditions of b but it wont read it

import java.util.Scanner;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        boolean b = true;

        do {
        
            Scanner scan = new Scanner(System.in);

            System.out.println("please enter a number to calculate the collatz conjecture ");
            String userNumber = scan.nextLine();

            int Number = Integer.parseInt(userNumber);

            do {

                double SecondNumber = (double) Number;
                if (SecondNumber / 2 != Number / 2) {
                    Number = Number * 3 + 1;
                    System.out.println(Number);

                }
                if (SecondNumber / 2 == Number / 2) {
                    Number = Number / 2;
                    System.out.println(Number);
                }
                Thread.sleep(250);

            } while (Number > 1);
            System.out.println("Would you like to run this program again? if so type yes then press enter");
            String f = scan.nextLine();
            if (f == "yes") {
                b = true;

            } else {
                b = false;
            }

        } while(b=true); /*for example this reads the first b without taking into account the other ones in between*/

    }
}

For some reason, it won't take into account the other variables under the same names. I've tried changing where the variable is read weather its the top or the bottom but I get the same outcome.

You need to change

} while (b=true);

To

} while (b==true);

or simply

} while (b);

The reason is that = is the set operator, and == is checking for equality

do {
        String f = scan.nextLine();
        if (f == "yes") {
            b = true;

        } else {
            b = false;
        }

    } while(b=true);
}

As others have pointed out, the problem is that you're assigning b=true immediately before checking if b is true, is you're always going to continue looping.

But there's a problem before that too: that's not how you check for string equality:

        if (f.equals("yes")) {
            b = true;

        } else {
            b = false;
        }

Or, easier:

b = f.equals("yes");

and update the loop condition to

} while (b);

Or, even easier again (because it doesn't involve an extra variable):

if (!f.equals("yes")) break;

And use while (true) as the loop condition.

While loop use to check the condition not for assigning the values to parameters.

while(b=true);

Here you are assigning value to be instead of checking the condition. You can use either of these solutions.

while(b==true);

or

while(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM