Problems with control flow structures using strings

73 views Asked by At

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;

    }

    }
  }  
}
2

There are 2 answers

1
giorashc On BEST ANSWER

This condition:

 if (!medium.equals("air") || !medium.equals("steel") || !medium.equals("water"))

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 OR medium == y OR medium == z)

the opposite will be:

(medium != x AND medium != y AND medium != z)

where in this case you want to print the error message.

0
Ankur Singhal On

Condition Expression is wrong

use this

 if (!medium.equals("air") && !medium.equals("steel") && !medium.equals("water"))

instead of

 if (!medium.equals("air")|| !medium.equals("steel")|| !medium.equals("water"))