Why does not my Do-While work...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • alireza6485
    New Member
    • Jan 2009
    • 19

    Why does not my Do-While work...

    Hi,
    This program prints Hi and ask the user "Print again" if user types"yes" the program should priny "Hi" and ask the question again.
    This is the code I wrote,for some reason the program does nothing when the user enter "yes",Pleas e fix the problem for me.
    Code:
    import java.util.Scanner;
    public class sample
    {
        public static void main(String [] args)
        {
         String again;   
    do{
            System.out.println("Hello");
            Scanner in=new Scanner(System.in);
            System.out.println("Print  again???");
            again=in.next();
    }
    while(again=="yes");
    }
    }
    my friend said I should change while(again=="y es") to again.equals("y es")
    Why should I do that?Why does not java like again=="yes"???
    Last edited by Frinavale; Oct 15 '09, 03:28 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.
  • pbrockway2
    Recognized Expert New Member
    • Nov 2007
    • 151

    #2
    Originally posted by alireza6485
    Hi,
    my friend said I should change while(again=="y es") to again.equals("y es")
    Why should I do that?Why does not java like again=="yes"???
    Your friend is right.

    The .equals() does something well documented: it returns true if and only if the two strings are made up of the same characters in the same order. This is exactly what you want and so you should use that method.

    == does something different. It is true if and only if the two references it is comparing have the same value. References have the same value when they refer (point to) the same object. In the case of strings it should be clear that you can have different strings made up of the same characters in the same order. (As an example look at the 5th and the 15th words in the previous sentence. One is near the start of the sentence, one is in the middle. They are clearly not "the same" in the sense of identical. But they are made up of the same characters in the same order.).

    An expression like new String("whateve r"); will always return a reference to a string that is not identical to any others. (That's what "new" means). But the string it refers (points) to may well be equal() to others.

    Comment

    • Yene
      New Member
      • Oct 2009
      • 13

      #3
      import java.util.Scann er;
      public class swing
      {
      public static void main(String [] args)
      {
      String again;
      do{
      System.out.prin tln("Hello");
      Scanner in=new Scanner(System. in);
      System.out.prin tln("Print again???");
      again=in.next() ;
      }
      while(again.equ als("yes"));
      }
      }
      This should work since == operator checks to see if two objects are exactly the same object.

      Comment

      Working...