简体   繁体   English

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

[英]If statement wont execute even though evaluation is true

In the following code, the block under if(timesout[entry] == "exit") will never execute. 在以下代码中, if(timesout[entry] == "exit")下的块将永远不会执行。 I have verified timesout[entry] for the current loop is set as "exit" in debugging mode, as well as by printing out the variable before the if statement is evaluated, but no matter what, the block never executes when I enter exit at the prompt, and I am stumped as to why. 我已经验证了当前循环的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;
    }
}
}
timesout[entry] == "exit"

use equals() to compare String, == compares reference equality 使用equals()比较字符串, ==比较引用相等

See 看到

Instead of 代替

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

use 采用

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

or 要么

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

more information different between == and equals() ==和equals()之间的更多信息有所不同

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

Can you try 你能试一下吗

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

instead of 代替

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

As @Jigar Joshi pointed you should see the difference and meaning of == and equals() 正如@Jigar Joshi指出的那样,您应该看到 ==equals()的区别和含义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM