Connecting Tech Pros Worldwide Forums | Help | Site Map

Why does not my Do-While work...

Newbie
 
Join Date: Jan 2009
Posts: 19
#1: Oct 15 '09
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",Please fix the problem for me.
Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2. public class sample
  3. {
  4.     public static void main(String [] args)
  5.     {
  6.      String again;   
  7. do{
  8.         System.out.println("Hello");
  9.         Scanner in=new Scanner(System.in);
  10.         System.out.println("Print  again???");
  11.         again=in.next();
  12. }
  13. while(again=="yes");
  14. }
  15. }
my friend said I should change while(again=="yes") to again.equals("yes")
Why should I do that?Why does not java like again=="yes"???

Member
 
Join Date: Nov 2007
Posts: 32
#2: Oct 15 '09

re: Why does not my Do-While work...


Quote:

Originally Posted by alireza6485 View Post

Hi,
my friend said I should change while(again=="yes") to again.equals("yes")
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("whatever"); 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.
Newbie
 
Join Date: Oct 2009
Posts: 9
#3: Oct 18 '09

re: Why does not my Do-While work...


import java.util.Scanner;
public class swing
{
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.equals("yes"));
}
}
This should work since == operator checks to see if two objects are exactly the same object.
Reply