2012-10-28 87 views
1

可能重複:
How do I compare strings in Java?無法獲得if語句工作

import java.util.Scanner; 

public class stringComparer { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner (System.in); 
     System.out.println ("Enter 1 word here - "); 
     String word1 = scan.next(); 

    System.out.println ("Enter another word here - "); 
    String word2 = scan.next(); 

    if (word1 == word2) { 
     System.out.println("They are the same"); 
    } 
} 
} 

我是有工作的約10分鐘前,改變了一些東西,現在它不顯示「他們是相同的」由於某種原因?它非常簡單,但我不明白我出錯的地方。

謝謝!

回答

1

==運算符通過引用比較對象

要找出兩個不同的String實例是否保持相同的值,請撥打.equals()

因此,

if (word1.equals(word2)) 
0

更換

if (word1 == word2) 

請試試這個它會工作,String is not primitive所以當u檢查==它將檢查引用。

import java.util.Scanner; 
/** 
* This program compares two strings 
* @author Andrew Gault 
* @version 28.10.2012 
*/ 
public class stringComparer 
{ 
    public static void main(String[] args) 
    { 
     Scanner scan = new Scanner (System.in); 
     System.out.println ("Enter 1 word here - "); 
     String word1 = scan.next(); 

    System.out.println ("Enter another word here - "); 
    String word2 = scan.next(); 

    if (word1.equals(word2)) 
    { 
     System.out.println("They are the same"); 
    } 

} 
} 
0

使用

if (word1.equals(word2)) 
{ 
System.out.println("They are the same"); 
} 

瞭解爲什麼here