Java – Strings and While loops


I think I'm having trouble with strings and while loops. When I run this program and I type in an action the program does nothing. It doesn't exit, it just sits there. That's why I think it's a problem with my while loop. But I think it could also be with my Strings right before the while loop. Am I declaring those Strings correctly? Or am I comparing them wrong in the while loop or something? Thanks for the help.

import java.util.Scanner;

public class HW2tester3 {

    public static void main(String args[]) {

        MotorBoat ex3 = new MotorBoat();
        Scanner keyboard = new Scanner(;
        System.out.printf("Input how fast the motorboat was going: ");
        int s = keyboard.nextInt();
        System.out.printf("Input the time the motorboat ran: ");
        int t = keyboard.nextInt();

        // 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) {
                else if (a == d) {
                else if (a == e) {
        if (a == b) {

Best Solution

a == b does not compare the value of two strings, but rather that a and b represent the same objects. Same for !=.

You want to use a.equals(b) not a == b.