Ros Zh
Ros Zh

Reputation: 11

Why deos my "While" loop keep going on?

My loop never stops, I can't seem to understand what is wrong. I'm doing a project for my class and I'm new to loops so kind of confused. Please tell me how to resolve this issue.

import java.util.Scanner;
public class FracCalc {
  public static void main(String[] args) {
       Scanner scan = new Scanner(System.in); {
        boolean Quit = true;

            System.out.println("Welcome to FracCalc");
            System.out.println("Type expressions with fractions, and I will evaluate them");
        String answer = scan.nextLine();
        while (Quit = true) {

        if (answer.equals("Quit")){
          System.out.println("Thanks forr running FracCalc!");
          break;  

        }   else {
          System.out.println("I can only process 'Quit' for now");

        }
        }
    }
  }

}

Upvotes: 0

Views: 237

Answers (2)

Ayb4btu
Ayb4btu

Reputation: 3378

Put String answer = scan.nextLine(); inside the loop.

Try the following:

import java.util.Scanner;
public class FracCalc {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Welcome to FracCalc");
        System.out.println("Type expressions with fractions, and I will evaluate them");

        String answer = scan.nextLine();

        do {

            if (answer.equals("Quit")) {
                System.out.println("Thanks forr running FracCalc!");
                break;  

            } else {
                System.out.println("I can only process 'Quit' for now");
            }

            answer = scan.nextLine();
        } while (true);
    }
}

Upvotes: 1

Amadan
Amadan

Reputation: 198294

Quit = true will assign true to Quit, and return true. Thus, you're doing while (true), a canonical infinite loop. And even if you were testing Quit == true (note double equality sign), you never assign it to false, as Izcd remarks. You could break out with your if, but answer is only assigned once, outside the loop.

Upvotes: 6

Related Questions