2

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");
    }
    }
}
Sky
  • 21
  • 1
  • 1
    If you don't specify value for static `quit`, it will be false (see [this](https://stackoverflow.com/questions/6226290/default-value-of-boolean-and-boolean-in-java)). Then it is never updated in your code to true. – Stanislav Poslavsky Jan 01 '20 at 01:34

3 Answers3

3

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);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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;
Salsabil
  • 15
  • 8
0

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");
    }
}
}
Anuradha
  • 570
  • 6
  • 20