对,在这个程序中我应该能够在列表中搜索一个人。如果我搜索不在列表中的人,则 Found 变量应保持为 false。如果我搜索列表中的某人,例如:“Ben”,则 Found 应设置为 true。
但是由于某种原因,搜索列表中的某人不会将找到设置为 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");
}
}
}
最佳答案
字符串是对象,并且使用 equals 方法检查对象相等性。
==
运算符用于对象引用相等(意味着两个引用是否指向同一个对象!)或基元(int,double,...)相等。
if(Names[Current-1] == PlayerName)
应该是
if(Names[Current-1].equals(PlayerName))
<小时/>
在这种情况下,如果 Names[Current-1]
为 null,则可能有机会获得 NullPointerExceotion
。为了避免这种情况java 7提供了一个静态的Utility类java.util.Objects
.
This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
所以最好的方法是 -
if(java.util.Objects.equals(Names[Current-1],PlayerName))
关于Java if 语句很愚蠢(简单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22005080/