1

My sentinel in below code won't work. It keeps looping instead of exiting when entering 'zzz'. Any ideas? Please note that i do wish to use Console class rather than Scanner class in this exercise.

class Username{
    public static void main(String[] args){
        String name, surname, code, username ;
        boolean sentinel = true ;
        do
        {
            System.out.print("enter name: ");
            name = Console.readString();

            System.out.print("enter surname: ");
            surname = Console.readString();

            System.out.print("enter code: ");
            code = Console.readString();

            username = surname + name.charAt(0) + code ;

            System.out.print("your username: " + username);

            System.out.println();

            System.out.print("enter zzz to stop or hit eneter to continue: ");
            String ans = Console.readString();
            if (ans == "zzz")
              sentinel = false ;
        }
        while (sentinel);
    }//end main
}//end class
Neeme Praks
  • 8,956
  • 5
  • 47
  • 47

3 Answers3

2

Change that to:

if (ans.equals("zzz"))
    sentinel = false ;

Or better yet to:

if ("zzz".equals(ans))
    sentinel = false ;

(This last version buys you a null check)

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
2

Use

if (ans.equals("zzz"))

instead of

if (ans == "zzz")

In Java, two strings are only "equal" if they are the same object... you have to use the equals() method to compare actual string contents.

Madison Caldwell
  • 862
  • 1
  • 7
  • 16
0

don't use == to compare strings use ans.equals("zzz")

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311