简体   繁体   中英

My do while loop is stopping after one iteration. how do I keep it going?

My code terminates after one iteration, even if quit is true.

import java.util.*;
public class calc {
public static  boolean quit;

    public static void main(String[] args) {
    keepGoing();
}
public static void keepGoing() {
    do {

        Scanner s = new Scanner(System.in);
        String input = s.nextLine();
        String inputLower = input.toLowerCase();
        int findQuit = inputLower.indexOf("quit");
        if (findQuit != -1) {
            boolean quit = false;
        }

    } while (quit == true); {
    System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
    }
    }
}

The default value of a boolean is false . So change

public static  boolean quit;

to

public static  boolean quit = true;

also you currently only set it to false with a shadowed variable. Change

if (findQuit != -1) {
    boolean quit = false;
}

to

if (findQuit != -1) {
    quit = false;
}

or eliminate the if and assign the boolean directly like

quit = (findQuit == -1);

Finally, there is no need to check if a boolean == true . Change

while (quit == true);

to

while (quit);

You have to initialize the variable quit first. Do it while definition or after but it has to be before the do while loop begining.

public static boolean quit = true;

You have to define the quit variable as true. Because default value of boolean variable is false.

public static boolean quit = true;

You need to change this code:

if (findQuit != -1) {
      boolean quit = false;
}

To:

if (findQuit != -1) {
      quit = false;
}

Because no need to define quite variable again.

No need to heck boolean using equals. So change the code from:

while (quit == true);
    {
        System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
    }

To:

while (quit);
    {
        System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
    }

Full code:

import java.util.*;

public class calc {
public static boolean quit = true;

public static void main(String[] args) {
    keepGoing();
}

public static void keepGoing() {
    do {

        Scanner s = new Scanner(System.in);
        String input = s.nextLine();
        String inputLower = input.toLowerCase();
        int findQuit = inputLower.indexOf("quit");
        if (findQuit != -1) {
            quit = false;
        }

    } while (quit);
    {
        System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
    }
}
}

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