Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

java - String.equals与== [重复](String.equals versus == [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?

(此代码将字符串分隔为标记并将它们存储在字符串数组中,然后将变量与第一个主页进行比较...为什么它不起作用?)

public static void main(String...aArguments) throws IOException {

    String usuario = "Jorman";
    String password = "14988611";

    String strDatos = "Jorman 14988611";
    StringTokenizer tokens = new StringTokenizer(strDatos, " ");
    int nDatos = tokens.countTokens();
    String[] datos = new String[nDatos];
    int i = 0;

    while (tokens.hasMoreTokens()) {
        String str = tokens.nextToken();
        datos[i] = str;
        i++;
    }

    //System.out.println (usuario);

    if ((datos[0] == usuario)) {
        System.out.println("WORKING");
    }
}
  ask by franvergara66 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the string.equals(Object other) function to compare strings, not the == operator.

(使用string.equals(Object other)函数来比较字符串,而不是==运算符。)

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal.

(该函数检查字符串的实际内容, ==运算符检查对象的引用是否相等。)

Note that string constants are usually "interned" such that two constants with the same value can actually be compared with == , but it's better not to rely on that.

(请注意,字符串常量通常是“实例化”,这样两个具有相同值的常量实际上可以与==进行比较,但最好不要依赖它。)

if (usuario.equals(datos[0])) {
    ...
}

NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.

(注意:比较是在'usuario'上完成的,因为你的代码中保证非null,尽管你仍然应该检查你在datos阵列中确实得到了一些标记,否则你会得到一个数组超出范围例外。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...