Wade J Wade J - 10 months ago 33
Java Question

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.in);
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) {


a == b checks whether a and b are the same object, which isn't always the case for strings. Use string.equals() instead.

Also, use variable names you can differentiate between. a, b, c, d, etc. are not good variable names and will frequently confuse you.

That being said, try this:

String input = "";

do {
  input = keyboard.nextLine();

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