1

在下面的代码中,下面的块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;
    }
}
}
4

3 回答 3

9
timesout[entry] == "exit"

用于equals()比较字符串,==比较引用相等

于 2012-09-03T05:46:39.040 回答
4

代替

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

采用

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

或者

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

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

 http://stackoverflow.com/questions/12171783/how-is-it-possible-for-two-string-objects-with-identical-values-not-to-be-equal/12171818#12171818 
于 2012-09-03T05:47:17.587 回答
1

你能试一下吗

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

代替

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

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

于 2012-09-03T05:48:45.150 回答