java - 字符串和 While 循环

标签 java string while-loop

我想我在处理字符串和 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 不比较两个字符串的值,而是比较 ab 代表相同的对象。 != 也是如此。

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

关于java - 字符串和 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9346466/

相关文章:

java - 使用Streams java从对象列表中获取成员列表

java - 将页面中的特定内容捕获为图像文件

Java 错误消息 "Cannot be resolved to a variable"?

java - 组织.hibernate.HibernateException : 'hibernate.dialect' must be set when no Connection available

python - 有没有更好的方法通过将 'object' 替换为 mean 来将 'na' 类型数组转换为 numpy 数组?

java - 如何在java中替换["with "“

java - do while循环设计有设计问题

java - 如何在不获取 "SomeType@2f92e0f4"的情况下打印我的 Java 对象?

python - 确保每个字母在密码中只出现一次

PHP 如果文件夹存在为每个子文件夹做一个循环