Java if 语句很愚蠢(简单)

标签 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");
    }
}
}

最佳答案

字符串是对象,并且使用 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.

Documentation

所以最好的方法是 -

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

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

相关文章:

python - 查找并替换 Pandas 数据框中的子字符串忽略大小写

javascript - 替换javascript中的某些字符

c - 插入排序 - C 中比较和交换的计数

java - 当 JSON 解析器找不到 JSON 对象时如何设置条件

Java 棋盘格,奇数/偶数 % 2 面板

java - 无法读取json文件: Spark Structured Streaming using java

python - 如何使列表接受/n,以便在写入文件时不让所有内容都在同一行?

linux - diff 文件只比较每行的前 n 个字符

java - 优化两个列表比较

java - 不确定如何将用户的输入(字符串)转换为可接受的数据类型