Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我的else语句不起作用?_Java_If Statement - Fatal编程技术网

Java 为什么我的else语句不起作用?

Java 为什么我的else语句不起作用?,java,if-statement,Java,If Statement,我正在尝试为我的编程课创建一个BART票价程序。然而,无论输入如何,我的结果总是-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(); Sy

我正在尝试为我的编程课创建一个BART票价程序。然而,无论输入如何,我的结果总是-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");
    }

}
首先,你的最后一个if缺少一个{

另一个问题是比较两个字符串的方式。请改用.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.");
    }