0

I would like to create option with do while were user after inputting correct letter will get out of the loop. I have try to make one but if I put while(type == "Y") it just throws me out of the loop doesn't matter what I press or if I out while(type != "Y") it is going in loop forever, so I am doing somewhere else wrong but I can not figure it out where.

public class JavaApplication8 {
static String type;
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    do {
        System.out.println("Press Y to get out of the loop");
        type = scanner.next();
    } while (type == "Y");

  }

}
Ronin
  • 39
  • 2
  • 3
  • 10

1 Answers1

2

Instead of

while (type == "Y");

use

while (type.equals("Y"));

== checks if two Strings refer to the same object
.equals() checks two objects contain the same data.

Also,it seems that you want to run the loop as long as the user does not enter Y.So change it to:

while (!type.equals("Y"));
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • Thank you for suggestion Cool Guy. I try equals but it still after I input any key other then "Y" it doesn't go in loop, it throws me out of loop. – Ronin Dec 14 '14 at 13:57