Below is method that asks for a medium that is either air, water, or steel. If what is entered isn't one of these, the programs ends. If it is a valid medium, it asks for a distance it will travel and calculates the time through each medium. The problem I am having is getting to the else statement.
Yes, this is a homework question. No, I'm not looking for the solution, just why the else and switches aren't being evaluated. I have already checked, and my jdk is version 7. Thanks in advance.
package speedofsound;
import java.util.Scanner;
public class SpeedOfSound {
public static void main(String[] args) {
String medium;
int distance, time;
Scanner read = new Scanner(System.in);
System.out.print("Enter one of the following: air, water, or steel: ");
medium = read.next();
if (!medium.equals("air")|| !medium.equals("steel")|| !medium.equals("water")){
System.out.print("Sorry, you must enter air, water, or steel.");
}
else {
System.out.print("Enter the distance the sound wave will travel: ");
distance = read.nextInt();
switch(medium){
case "air":
time = distance/1100;
System.out.println("It will take "+time+ "seconds.");
break;
case "water":
time = distance/4900;
System.out.println("It will take "+time+ "seconds.");
break;
case "steel":
time = distance/16400;
System.out.println("It will take "+time+ "seconds.");
break;
}
}
}
}
This condition:
is incorrect. Replace the
||
with&&
.It might be a bit confusing when you think about it literally but
medium
can only be equal to one value so you want to make sure that:(
medium
== x ORmedium
== y ORmedium
== z)the opposite will be:
(
medium
!= x ANDmedium
!= y ANDmedium
!= z)where in this case you want to print the error message.