-1
package cheapoplanner;

import java.util.Scanner;

public class Travel extends CheapoPlanner {

    protected int passenger;
    protected double trainRate = 0.15;
    protected boolean hasCar;
    protected int carParkingFee = 30;
    protected int milesToAirport;
    protected double carRate = 0.30;
    protected double flightRate = 0.10;
    protected int milesFlying;
    protected double coachRate = 0.50;
    protected int milesToDestination;
    protected String startLetter;
    protected String endLetter;

    Scanner sc = new Scanner(System.in);

    protected void lengthChecker(String startLetter, String endLetter) {

    }

    protected boolean lettersDoMatch() {

        if (startLetter.toLowerCase() == endLetter.toLowerCase()) {
            return true;
        } else {
            return false;
        }
    }

    protected void greeting() {
        System.out.print("What is your first airport? (Choose A, B, C, D, or E): ");
        startLetter = sc.nextLine();
        System.out.print("What is your destination? (Choose A, B, C, D, or E): ");
        endLetter = sc.nextLine();

        if (lettersDoMatch() == true) {
            System.out.println("letters can't match");
            greeting();
        }

        System.out.println("code past last pt.");
    }
}

In my main method, I called the greeting() method. The goal is to validate that the airport and destination are not the same letter. This is done in the lettersDoMatch() method. Whatever value gets returned, in greeting() I do a logic compare. If it's true (which it shouldn't be), I print out a warning and it should go back to the beginning of the greeting function. Otherwise, I'm expecting that that block of code gets skipped. I'm confused though, because when I run my code, when I type in two letters that are the same, it doesn't go to the beginning of greeting() method again. What happens is that I go straight to "code past last pt". Is my issue something in the greeting() method? Or something in the lettersDoMatch() method? Or a combo of things?

khelwood
  • 55,782
  • 14
  • 81
  • 108
irradio
  • 53
  • 7
  • String comparation in java: `startLetter.toLowerCase().equals(endLetter.toLowerCase())` – Krayo Oct 02 '14 at 13:44
  • 1
    possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – njzk2 Oct 02 '14 at 13:45

1 Answers1

1
if (startLetter.toLowerCase() == endLetter.toLowerCase()) {

should be

if (startLetter.toLowerCase().equals(endLetter.toLowerCase())) {

or

if (startLetter.equalsIgnoreCase(endLetter)) {

Comparing strings with == in Java doesn't compare their content. That's why there are equals methods.

See How do I compare strings in Java?

You could just simplify the method to:

protected boolean lettersDoMatch() {
    return startLetter.equalsIgnoreCase(endLetter);
}
Community
  • 1
  • 1
khelwood
  • 55,782
  • 14
  • 81
  • 108