这是我在Java课上的第一个作业,我已经很沮丧了,哈哈。新来的新人。
我想这样做,所以我可以输入LAX或SAN或LAS,它将继续并在我的if语句下列出其他语句。相反,它总是直接转到else语句下,即使我确实输入了"LAX"例如在控制台中。
我有:
import java.util.Scanner;
public class MilesCalculator {
public static void main(String[] args) {
String airCode = "";
System.out.println("tttMiles Calculatorn");
System.out.println("This program will calculate how many miles you earn on your Phoenix Air Flight.n");
System.out.println("DESTINATIONS");
System.out.println("Los Angeles (LAX)");
System.out.println("San Diego (SAN)");
System.out.println("Las Vegas (LAS)n");
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter the destination airport code: ");
airCode = scnr.nextLine();
if (airCode == "LAX" || airCode == "SAN" || airCode == "LAS") {
System.out.println("STATUS");
System.out.println("1. Bronze");
System.out.println("2. Silver");
System.out.println("3. Gold");
System.out.println("4. Platinumn");
System.out.print("Please enter your frequent flyer status option (1-4): ");
}
else {
System.out.printf("Phoenix Air does not fly to %s. There will be zero miles earned. nPress enter to quit...", airCode);
System.exit(0);
scnr.nextLine();
}
在Java中比较字符串时,不能使用==
。您必须使用equals
或equalsIgnoreCase
,如下所示:
if (airCode.equals("LAX") || airCode.equals("SAN") || airCode.equals("LAS")) {
为什么有很多解释,但在你刚开始编程的时候,我会说"接受它"。现在。以后你一定会明白为什么。
比较字符串时不要使用(==)//这是错误的做法,而是使用String.equals()函数或者String.equalsIgnoreCase()函数然后在参数
中指定要比较的内容E。g if(airCode.equals(" LAX") || air code.equals("SAN") || airCode.equals("LAS")