字符串和while循环

时间:2012-02-19 03:35:18

标签: java string while-loop

我认为我在使用字符串和while循环时遇到了麻烦。当我运行这个程序并输入一个动作时,程序什么都不做。它不会退出,只是坐在那里。这就是为什么我认为这是我的while循环的问题。但我认为它也可能在我的Strings之前就在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);
        }
    }
}

4 个答案:

答案 0 :(得分:4)

a == b不会比较两个字符串的值,而是ab表示相同的对象。与!=相同。

您想使用a.equals(b)而不是a == b

答案 1 :(得分:2)

a == b检查ab是否是同一个对象,但字符串并不总是如此。请改用string.equals()

另外,使用可以区分的变量名称。 abcd不是好的变量名称,并且经常会让您感到困惑。

话虽如此,试试这个:

String input = "";

do {
  input = keyboard.nextLine();

  if (input.equals("distance")) {
    ex3.getDistance();
  } else if (input.equals("fuel")) {
      ex3.getFuelUsed();
  } else if (input.equals("refuel")) {
      ex3.Refuel();
  }
} while (!input.equals("done"));

System.exit(0);

答案 2 :(得分:1)

在java中,您无法将字符串与==或!=

进行比较

使用a.equals(b)!a.equals(b)

答案 3 :(得分:1)

“==”运算符可用于测试原始值是否相等(即int,char,boolean ...)。

但是,当您使用“==”运算符比较两个对象引用变量时,实际上是在测试这两个引用是否指向同一个对象。

Rectangle box1 = new Rectangle(5, 10, 20, 30); 
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);

比较

box1 == box2; // true;

比较

box1 == box3; // false;

要比较对象的内容,请使用equals(Object)方法,如果两个对象具有相同的内容,则返回true。

String a = "distance";
String b = "done";
if(a.equals(b)){
  //code...
}
相关问题