我想我在处理字符串和 while 循环时遇到了问题。当我运行这个程序并输入一个 Action 时,程序什么都不做。它不会退出,它只是坐在那里。这就是为什么我认为这是我的 while 循环的问题。但我认为它也可能在 while 循环之前与我的字符串一起使用。我是否正确声明了这些字符串?或者我在 while 循环中比较它们是错误的还是什么?感谢您的帮助。
import java.util.Scanner;
public class HW2tester3 {
public static void main(String args[]) {
MotorBoat ex3 = new MotorBoat();
Scanner keyboard = new Scanner(System.in);
System.out.printf("Input how fast the motorboat was going: ");
int s = keyboard.nextInt();
ex3.ChangeSpeed(s);
System.out.printf("Input the time the motorboat ran: ");
int t = keyboard.nextInt();
ex3.OperatingTime(t);
// Ask the user what action he or she wants to take
System.out.printf("If you want your distance travelled type:" +
" distance\n");
System.out.printf("If you want how much fuel you used type: fuel\n");
System.out.printf("If you want to refuel type: refuel\n");
System.out.printf("If you are finished type: done\n");
System.out.printf("What would you like to do? ");
// Compares the input with the defined strings and preforms the
// the action requested
String a = keyboard.nextLine();
String b = "done";
String c = "distance";
String d = "fuel";
String e = "refuel";
if (a != b) {
while (a != b) {
a = keyboard.nextLine();
if (a == c) {
ex3.getDistance();
}
else if (a == d) {
ex3.getFuelUsed();
}
else if (a == e) {
ex3.Refuel();
}
}
}
if (a == b) {
System.exit(0);
}
}
}
最佳答案
a == b
不比较两个字符串的值,而是比较 a
和 b
代表相同的对象。 !=
也是如此。
您想使用 a.equals(b)
而不是 a == b
。
关于java - 字符串和 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9346466/