2014-02-25 55 views
0

對,在這個程序中,我應該能夠搜索列表中的某個人。如果我搜索不在列表中的人,那麼Found變量應該保持爲false。如果我搜索列表中的某人,例如:「Ben」,那麼Found應該設置爲true。Java如果語句很蠢(簡單)

但是由於某種原因,搜索列表中的某個人並未將其設置爲true。看起來像檢查玩家對陣列輸入的if語句無法正常工作。我不知道這是爲什麼。沒有錯誤。誰能幫忙?由於

代碼:

package com.test.main; 

import java.util.Scanner; 

    public class Main { 
    public static void main(String[] args){ 
    String[] Names = new String[4]; 
    Names[0] = "Ben"; 
    Names[1] = "Thor"; 
    Names[2] = "Zoe"; 
    Names[3] = "Kate"; 

    int Max = 4; 
    int Current = 1; 
    boolean Found = false; 

    System.out.println("What player are you looking for?"); 
    Scanner scanner = new Scanner(System.in); 
    String PlayerName = scanner.nextLine(); 

    while(!Found && Current <= Max){ 
     //System.out.println(Names[Current-1]); 
     //System.out.println("PLAYERNAME: " + PlayerName.length() + ", ARRAY: " + Names[Current-1].length()); 
     if(Names[Current-1] == PlayerName){ 
      //System.out.println("found"); 
      Found = true; 
     } 
     else{ 
      Current++; 
     } 
    } 
    //System.out.println(Found); 
    if(Found){ 
     System.out.println("Yes, they have a top score"); 
    } 
    else{ 
     System.out.println("No, they do not have a top score"); 
    } 
} 
} 
+5

閱讀[我如何在Java中比較字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – PakkuDon

+0

使用String.equals方法而不是==比較字符串值 –

+0

...你會意識到if(Names [Current-1] == PlayerName){'應該是if(Names [Current-1] .equals(PlayerName) ){'。 – SudoRahul

回答

0
您正在使用的比較基準,而不是價值String對象

嘗試:

if (PlayerName.equals(Names[Current-1])) { 
    ... 
} 
1

字符串是對象和與對象相等檢查equals方法。

==運算符用於對象引用相等(意味着兩個引用指向相同的對象或不!)或基元(int,double,...)相等。

if(Names[Current-1] == PlayerName) 

應該

if(Names[Current-1].equals(PlayerName)) 

在這種情況下,有可能會得到NullPointerExceotion如果Names[Current-1]是空的機會。爲了避免這種情況,java 7提供了一個靜態實用程序類java.util.Objects

此類包含用於在 對象上操作的靜態實用方法。這些實用程序包括用於計算對象的哈希碼,返回對象的字符串以及比較兩個對象的空安全或空容忍方法 。

Documentation

所以最好的辦法是 -

if(java.util.Objects.equals(Names[Current-1],PlayerName)) 
+0

啊,謝謝! – user3195474

0

使用的名稱[當前-1] .equals(PlayerName)而不是名稱[當前-1] == PlayerName

0

我不知道您是否對集合有所瞭解,但以下代碼將簡化您的工作。上述代碼失敗的原因是您使用「==」而不是「equals」。而對於你的孩子來說,總是有一個習慣,用小寫字母開頭的變量名。 playerName

public static void main(String[] args) { 

    List<String> names = new ArrayList<String>(); 
    names.add("Ben"); 
    names.add("Thor"); 
    names.add("Zoe"); 
    names.add("Kate"); 

    boolean found = false; 

    System.out.println("What player are you looking for?"); 
    Scanner scanner = new Scanner(System.in); 
    String playerName = scanner.nextLine(); 

    for (String name : names) { 
     if (playerName.equalsIgnoreCase(name)) 
      found = true; 
    } 
    // System.out.println(Found); 
    if (found) { 
     System.out.println("Yes, they have a top score"); 
    } else { 
     System.out.println("No, they do not have a top score"); 
    } 
}