-3

I have following do while code, where I am trying to end the loop when the text entered is Stop. However even though when I type Stop in the console, it doesn't work. I tried to debug it and see it tries to compare the Stop text but doesn't stops it. I don't understand what is the problem. This is a java code running in eclipse.

import java.util.Scanner;

public class Application8_Switch {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a string to match the output");
    String text;
    do {
      text = input.nextLine();
      switch (text) {

        case "start":
          System.out.println("Machine started");
          break;

        case "end":
          System.out.println("This Machine stopped");
          break;

        default:
          System.out.println("Command not recognized");
          break;
      }

    } while (text != "Stop");


  }
}
AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66

2 Answers2

1

Try this:

Scanner input = new Scanner(System.in);
        System.out.println("Enter a string to match the output");
        String text;
        do {
            text = input.nextLine();
            switch (text) {

            case "start":
                System.out.println("Machine started");
                break;

            case "end":
                System.out.println("This Machine stopped");
                break;

            default:
                System.out.println("Command not recognized");
                break;
            }
        } while (!text.equals("Stop"));

Modifications:

  1. Used !text.equals("Stop") because == checks by comparing references. However You need to use equals() method to check its content.
Nitin Bisht
  • 5,053
  • 4
  • 14
  • 26
0

Strings in Java aren't compared using == or != like you think they would be.

Instead of using text != "Stop", use !text.Equals("Stop").

absoluteAquarian
  • 510
  • 3
  • 12