0

Here's my code. I'm super noobie so don't flame me too hard haha. I've tried a few different ways, and looked at numerous posts and sites about how to close loops. I think the problem is that (i==("quit")) is not recognizing when the user types in quit. It just loops infinitely through making me input a new word and telling me it's the wrong word.

heres the code.

package monty;
import java.io.*;
import java.io.Console;
import java.util.Arrays;
import java.io.IOException;
import java.util.Scanner;

public class firsttry2 {

public static void main(String[] args) {

    System.out.print("Enter the word 'quit' to end this program. Otherwise, it will run indefinitely.");

    int x=0;
    Scanner in=new Scanner(System.in);

     while (x<1) {


         String i;

        i=in.next();

        if (i==("quit")) {x++; in.close(); break;}
        else {System.out.print("You did not enter the word 'quit'. Please try again ."); 
        }
    }

}

}

thanks for any help you guys can give me! I also tried it with while (true) and couldn't get that to work either. same result, doesn't recognize when i type 'quit'.

2 Answers2

4

best alternate would be i.equals("quit") instead of i==("quit") The reason is == and equals() are not same.Below explains the difference

== checks for identity. That is whether the two objects are the same object and point to the same address in memory.

.equals() by default does the same thing, but can be overridden to perform different equality comparisons. (i.e. strings are considered equal if they have the same characters in the same order)

If you want users can also write quit or Quit then instead of equals() you can also use equalsIgnoreCase()

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
2

You have made the very common mistake of using the == operator to compare strings in Java. You need to use the equals() function. You can learn more about it here.

Community
  • 1
  • 1
David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122