This question already has answers here:
How do I compare strings in Java?

(23个答案)


6年前关闭。





是的,在此程序中,我应该能够在列表中搜索一个人。如果我搜索不在列表中的某个人,则Found变量应保持为false。如果我搜索列表中的某人,例如:“ Ben”,则Found应该设置为true。

但是由于某种原因,搜索列表中的某人未将found设置为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))




在这种情况下,如果NullPointerExceotion为null,则可能会得到Names[Current-1]。为了避免这种情况,java 7提供了一个静态实用程序类java.util.Objects


此类包含用于操作的静态实用程序方法
对象。这些实用程序包括null安全或null容忍的方法
用于计算对象的哈希码,并为
对象,并比较两个对象。


Documentation

所以最好的方法是-

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

关于java - Java if语句很愚蠢(简单),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22005080/

10-11 21:59
查看更多