【发布时间】: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;
}
}
}
【问题讨论】:
-
对于字符串总是使用 .equals() 来比较。
-
Java tag wiki 收集了一些常见问题。比较字符串是 Java 程序员遇到的许多常见问题之一。
标签: java