對,在這個程序中,我應該能夠搜索列表中的某個人。如果我搜索不在列表中的人,那麼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");
}
}
}
閱讀[我如何在Java中比較字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – PakkuDon
使用String.equals方法而不是==比較字符串值 –
...你會意識到if(Names [Current-1] == PlayerName){'應該是if(Names [Current-1] .equals(PlayerName) ){'。 – SudoRahul