简体   繁体   中英

Compare user input to a string with if else statement

the program is suppose to ask the user to enter an element of water, air, and steel. Then they have to input how far they want it to go. the problem i'm having is i cant get the element to equal air so it can execute the formula. I know that the if -else is a mess that was me trying to figure out what works. Any answer appreciated.

public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);
    System.out.println("enter an element of water,air,or steel");           

    String element=sc.next();
    System.out.println("how far do you want it to travel, dont use any unit of measurment");
    double distance=sc.nextInt();
    double time1=distance/1100;
    double time2=distance/4900;
    double time3=distance/16400;    

            if (element.equals(air)){
                System.out.println("the time is "+time1);       }
            else if(element.equals.water)
                System.out.println("the time is "+time2);

            else if(element.equals.steel)
                System.out.println(time3);





        }

}

Just use element.equalsIgnoreCase("air") or for example this code:

switch (element.toLowerCase()) {
    case "air": ...
    case "water": ...
    case "steel": ...
}

Why did you omit quotation marks while comparing the strings? This is how it should look:

if (element.equals("air")) {
    System.out.println("the time is " + time1);
} else if (element.equals("water"))
    System.out.println("the time is " + time2);
else if (element.equals("steel"))
    System.out.println(time3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM