【发布时间】:2012-03-09 22:16:24
【问题描述】:
我认为我在使用字符串和 while 循环时遇到了问题。当我运行这个程序并输入一个动作时,程序什么也不做。它没有退出,它只是坐在那里。这就是为什么我认为这是我的 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,那会发生什么?
if语句的哪个分支被执行?那么接下来会发生什么?keyboard.nextLine()被评估了多少次?请更新问题,并从if( a!=b)行开始逐步分析。
标签: java string while-loop