簡體   English   中英

如果即使評估為真,語句也不會執行

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

在以下代碼中, 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;
    }
}
}
timesout[entry] == "exit"

使用equals()比較字符串, ==比較引用相等

看到

代替

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 

你能試一下嗎

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

代替

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

正如@Jigar Joshi指出的那樣,您應該看到 ==equals()的區別和含義

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM