2011-08-20 9 views
-3
import java.util.Scanner; 

class Test6 
{ 
    public static void main (String[] args) 
    { 
     int z = 0; 
     while (z != 1) 
     { 
      System.out.print("Please enter your name: "); 
      Scanner x = new Scanner (System.in); 
      String name = x.nextLine(); 
      System.out.print("\n"+"So your name is "+name+"?: "); 
      Scanner y = new Scanner (System.in); 
      String answer = y.nextLine(); 
      if ((answer == "yes")||(answer == "Yes")); 
      { 
       z = 1; 
      } 
     } 
     System.out.println("\n"+"Great!"); 
    } 
} 
+1

? –

+1

@Mr。失望循環永不結束? ;-)(儘管可能會發生什麼呢,它會永遠,永遠「正常」結束的代碼。) – 2011-08-20 19:16:31

+0

@pst:哦,我還以爲是一個特點,決定這傢伙只是不喜歡祭出奉承。 ;) –

回答

1

使用String#equals(),不==。已經有many questions on SO了。

if ("yes".equals(answer) || "Yes".equals(answer)); 
{ 
    z = 1; 
} 

在你的情況,String#equalsIgnoreCase()可能更適合:

if ("yes".equalsIgnoreCase(answer)); 
{ 
    z = 1; 
} 

旁註:你正在使用z像一個布爾標誌。相反,使用int的,使用boolean

boolean z = true; 
while (z) 
{ 

} 
+0

但是*爲什麼*它有什麼關係? ;-)爲什麼首先是「是」? – 2011-08-20 19:14:57

+0

我通常寧願與左側的字符串文字進行比較以確保null安全。 –

2

使用"yes".equalsIgnoreCase(answer)

+0

爲什麼先放「是」? – 2011-08-20 19:15:44

+0

@pst:[尤達條件](http://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)。 –

+0

但是在Java中與「Yoda條件」相關嗎?因爲當意圖相等時忽略布爾賦值是不可能錯誤地使用賦值的嗎?特別是因爲我們正在使用方法調用,而不是操作符... – maerics

0

String對象將工作在調用equals("str")

if(answer.equals("yes") || answer.equals("no")) 
{ 
    z = 1; 
} 

==與字符串進行比較的引用,如String在Java是一個對象。

1

你想看看String.equals()String.equalsIgnoreCase(),例如answer.equalsIgnoreCase("yes")或甚至"yes".equalsIgnoreCase(answer)

1

使用等於或你的情況可能會equalsIgnoreCase

if(answer.equalsIgnoreCase("yes")) 
{ 

} 
0

你感到困惑的object identity and object equality的概念。

在Java編程語言中,等號運算符(==)測試左側和右側操作數是否引用相同的確切對象(又稱引用相等或對象標識);然而,Object#equals(o) method(被String類重寫)測試調用對象是否與其參數「等價」。

考慮這些例子:

String s = "foo"; 
s == s; // => true, because the variable "s" obviously refers 
// to the same object as itself. They are "identical". 

在另一方面:你究竟有什麼問題

String a = new String("foo"); 
String b = new String("foo"); 
a == b; // => false, because there are two separate objects. 
// However... 
a.equals(b); // => true, because the strings have the same 
// character sequences. They are "equal".