为什么我的其他if语句不起作用?

时间:2015-02-14 17:01:20

标签: java if-statement

我正在尝试为我的编程课程创建一个BART Fare程序。但无论输入如何,我的结果总是-1。为什么我的程序会遵循else if语句?

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);

    System.out.println("Please enter the ticket type: ");
    String type = input.nextLine();

    System.out.println("Please enter the zone number: ");
    int zone = input.nextInt();

    if ((zone <= 2) && (type == "adult")){
        System.out.println("The fare is 20.");
    }   else if ((zone <= 2) && (type == "child")){
        System.out.println("The fare is 10.5.");
    }   else if ((zone == 3) && (type == "adult")){
        System.out.println("The fare is 30.5.");
    }   else if ((zone == 3) && (type == "child")){
        System.out.println("The fare is 20.");
    }   else if ((zone == 4) && (type == "child")){
        System.out.println("The fare is 20.");
    }   else if ((zone == 4) && (type == "adult")){
        System.out.println("The fare is 43.");
    }   else if ((zone > 4) || (type != "adult") || (type != "child"))
        System.out.println("-1");
    }

}

1 个答案:

答案 0 :(得分:1)

首先,您的上一个else if错过了&#34; {&#34;

您的另一个问题是您将两个字符串进行比较的方式。请改用.equals()

这是一个例子。采取第一个if语句

你有:

if ((zone <= 2) && (type == "adult")){
        System.out.println("The fare is 20.");
    }

尝试:

if ((zone <= 2) && (type.equals("adult"))){
        System.out.println("The fare is 20.");
    } 

此比较比较字符串值。对其余的比较执行此操作,您应该看到所需的结果。