开发者

do while sentinel not working (java)

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


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.


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜