Java if语句很愚蠢(简单)

时间:2014-02-25 05:04:54

标签: java string comparison

是的,在这个程序中,我应该能够在列表中搜索一个人。如果我搜索不在列表中的某人,则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");
    }
}
}

4 个答案:

答案 0 :(得分:1)

String是使用equals方法检查对象和对象的相等性。

==运算符用于对象引用相等(意味着两个引用指向同一个对象或不指向!)或原始(int,double,...)相等。

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

应该是

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

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

  

此类包含用于操作的静态实用程序方法   对象。这些实用程序包括null-safe或null-tolerant方法   用于计算对象的哈希码,返回一个字符串   对象,并比较两个对象。

Documentation

所以最好的方法是 -

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

答案 1 :(得分:0)

您正在使用String对象来比较引用而不是值。

尝试:

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

答案 2 :(得分:0)

使用名称[Current-1] .equals(PlayerName)代替名称[Current-1] == PlayerName

答案 3 :(得分: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");
    }
}
相关问题