Wade J Wade J - 7 months ago 13
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();
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);
}
}
}

Answer

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")) {
    ex3.getDistance();
  } else if (input.equals("fuel")) {
      ex3.getFuelUsed();
  } else if (input.equals("refuel")) {
      ex3.Refuel();
  }
} while (!input.equals("done"));

System.exit(0);