【问题标题】:If statement wont execute even though evaluation is true即使评估为真,if 语句也不会执行
【发布时间】:2012-09-03 13:55:56
【问题描述】:

在下面的代码中,if(timesout[entry] == "exit") 下的块永远不会执行。我已经验证了timesout[entry],因为当前循环在调试模式下设置为“退出”,并且在评估 if 语句之前打印出变量,但无论如何,当我输入 exit 时,该块永远不会执行在提示符下,我不知道为什么。

import java.util.Scanner;

public class timetracker {
public static void main(String args[]) {
    boolean exit = false;
    String[] reasons = new String[30];
    String[] timesout = new String[30];
    String[] timesin = new String[30];
    int entry = 0;
    Scanner keyinput = new Scanner(System.in);

    recordloop:
    while(exit == false) {
        //record info



        System.out.println("Enter time out:");
        timesout[entry] = keyinput.nextLine();

        if(timesout[entry] == "exit") {
            exit = true;
            break recordloop;   
        }

        System.out.println("Enter reason:");
        reasons[entry] = keyinput.nextLine();
        System.out.println("Enter time in:");
        timesin[entry] = keyinput.nextLine();

        entry = entry + 1;

    }

    System.out.println("Times away from phone:\n ----- \n");
    int count = entry;
    entry = entry + 1;

    while(count < entry) {
        System.out.println(reasons[count] + ": " + timesout[count] + " - " + timesin[count] + "\n");
        count = count + 1;
    }
}
}

【问题讨论】:

标签: java


【解决方案1】:
timesout[entry] == "exit"

使用equals()比较String,==比较引用相等

【讨论】:

  • 哇。我是一名 c# 程序员,所以我也会为此苦苦挣扎。那么这是否意味着 java 不使用不可变字符串?别担心,我会谷歌它;-)
  • java 可以,但是它不会缓存池中的所有字符串,所以最好使用 equals() 来比较对象是否相等
  • 啊,是的,谷歌快速搜索也发现了这一点,谢谢。奇怪的是,将字符串变量与字符串文字进行比较不会导致编译器警告,那么呢?我的意思是,程序员想要做什么非常清楚(而且我想不出我想检查我的变量是否引用了在“后端”中为我创建的相同字符串来表示我的文字)。
  • 谢谢!我天生就是 PHP 程序员,所以我不确定这里发生了什么。
  • String 将实例缓存在文字池中,您可以在其中简单地比较它们是否相等,然后两个 Object 都相同,因此相等
【解决方案2】:

代替

if(timesout[entry] == "exit") 

使用

if(timesout[entry].equals("exit"))

if("exit".equals(timesout[entry]))

== 和 equals() 之间的更多信息不同

 http://*.com/questions/12171783/how-is-it-possible-for-two-string-objects-with-identical-values-not-to-be-equal/12171818#12171818 

【讨论】:

    【解决方案3】:

    你可以试试

    if("exit".equals(timesout[entry]))
    

    而不是

    if(timesout[entry] == "exit")
    

    正如@Jigar Joshi所指出的,你应该see==equals()的区别和含义

    【讨论】:

      最近更新 更多