2012-11-27 66 views
-1

可能重複:
How do I compare strings in Java?爲什麼按「y」時不打印任何內容並進入?

我真的不明白,爲什麼下面的程序不顯示任何東西,當我寫「Y」,然後按回車。

import java.util.Scanner; 

public class desmond { 
    public static void main(String[] args){ 
     String test; 
     System.out.println("welcome in our quiz, for continue write y and press enter"); 
     Scanner scan = new Scanner(System.in); 
     test = scan.nextLine(); 
     if (test == "y") { 
      System.out.println("1. question for you"); 
     } 
    } 
} 
+2

在'if'中使用'test.equals(「y」)' –

回答

3

使用equals()比較字符串

test.equals("y") 

even better

"y".equals(test) 
+0

非常感謝。 –

2

你(一般)需要與equals在Java中比較字符串:

if ("y".equals(test)) 
1

你可以使用==比較字符串嗎?是。 100%的時間工作?編號

我在java中開始編程時首先學到的東西之一是從不使用==來比較字符串,但是爲什麼?我們來看一個技術性的解釋。

字符串是一個對象,如果兩個字符串具有相同的對象,方法equals(Object)將返回true。如果兩個引用的String引用指向同一個對象,==運算符將只返回true。

當我們創建一個字符串時,實際上創建了一個字符串池,當我們創建另一個具有相同值的字符串時,如果JVM需求已經存在,那麼字符串池中具有相同值的字符串(如果有的話)指向相同的內存地址。

因此,當您使用「==」測試變量「a」和「b」的相等性時,可能會返回true。

例子:

String a = "abc"// string pool 
String b = "abc";/* already exists a string with the same content in the pool, 
                                  go to the same reference in memory */
String c = "dda"// go to a new reference of memory as there is in pool 

如果創建的字符串,所以你是在內存中創建一個新的對象和測試變量與「==」,則返回false平等和b,它沒有指向到內存中的同一個地方。

String d = new String ("abc")// Create a new object in memory 

String a = "abc"; 
String b = "abc"; 
String c = "dda"; 
String d = new String ("abc"); 


a == b = true 
a == c = false 
a == d = false 
a.equals (d) = true 
相關問題