ChunkierLizard ChunkierLizard - 1 year ago 81
Java Question

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.out.println("enter an element of water,air,or steel");

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)



Answer Source

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"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download