Andy Ahn
Andy Ahn

Reputation: 1

Java with switch

i'm not entirely sure what is wrong with this java. i kept getting incompatible type when i run the program. I am only a beginner in java program. Please give me a hand in detail. i have tried various method and searched for many links in google. but i was just unfortunate. Write a program that asks the user to enter “air”, “water”, or “steel”, and the distance that a sound wave will travel in the medium. The program should then display the amount of time it will take.

Prompts And Output . The program prompts for the medium with: "Enter one of the following: air, water, or steel: " and reads the medium. If the medium is not air, water or steel the program prints the message : "Sorry, you must enter air, water, or steel." an nothing else. Otherwise the program prompts for the distance with ("Enter the distance the sound wave will travel: " and reads it in and then prints "It will take x seconds." where x is the time calculated by your program .

and this is what I have so far.

class one{ 
    public static void main(String[] args){ 
        Scanner input = new Scanner(System.in);

        System.out.print("Enter one of the following: air, water, or steel: ");
        String text = input.nextLine();

        System.out.print("Enter the distance the sound wave will travel: ");

        double distance;
        double time;

        distance = input.nextDouble();

        switch (text){
            case "air":
                time = (distance/1100);
                System.out.println("It will take " + time + " sconds." );
                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;


            default:
                System.out.println("Sorry, you must enter air, water, or steel.");
        }    
    }
}

Upvotes: 0

Views: 262

Answers (2)

Dyrandz Famador
Dyrandz Famador

Reputation: 4525

so your compiler might be lower version.. switch in string will not work in Java 6 and before.

upgrade your JDK to higher version. Download latest JKD here

in the JDK 7 release, you can use a String object in the expression of a switch statement:

Instead of using alternative like if else,

It would be better to upgrade your JDK.

note: String objects in switch statements is case sensitive so before comparing the string, you can make the inputted string to uppercase 'coz the switch statement is case sensitive.

Upvotes: 0

Astra Bear
Astra Bear

Reputation: 2738

What version of Java are you using? Cannot use switch on a String in versions < Java 7. See Why can't I switch on a String?

Also suggest you use something like Eclipse to code Java which will pick up these errors.

Upvotes: 2

Related Questions