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.");
}
}
在我的main方法中,我调用了greeting()方法。目标是验证机场和目的地不是同一个字母。这是在lettersDoMatch()方法中完成的。无论返回什么值,在greeting()中我都会进行逻辑比较。如果它是真的(它不应该是),我打印出一个警告,它应该回到问候功能的开头。否则,我希望跳过该代码块。我很困惑,因为当我运行我的代码时,当我输入两个相同的字母时,它不会再次转到greeting()方法的开头。会发生什么事情,我直接去了#34;代码经过最后一次"。我的问题是在greeting()方法中的吗?或者在lettersDoMatch()方法中有什么东西?还是一组东西?
答案 0 :(得分:1)
if (startLetter.toLowerCase() == endLetter.toLowerCase()) {
应该是
if (startLetter.toLowerCase().equals(endLetter.toLowerCase())) {
或
if (startLetter.equalsIgnoreCase(endLetter)) {
在Java中将字符串与==
进行比较并不能比较它们的内容。这就是equals
种方法的原因。
请参阅How do I compare strings in Java?
您可以简化方法:
protected boolean lettersDoMatch() {
return startLetter.equalsIgnoreCase(endLetter);
}