即使评估为真,语句也不会执行

Mor*_*gan 1 java

在下面的代码中,下面的块if(timesout[entry] == "exit")将永远不会执行.我已经验证timesout[entry]了当前循环在调试模式下被设置为"exit",以及在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;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Jig*_*shi 9

timesout[entry] == "exit"
Run Code Online (Sandbox Code Playgroud)

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

看到

  • java确实如此,但它不会缓存池中的所有String,因此最好使用equals()来比较Object的相等性 (3认同)