Hi I'm new to Java. I am trying to write a program that allows the user to select a medium to calculate the speed of sound. The user will need to choose a medium (air, water, steel) & then input how far the sound wave will travel. I have to create a menu with the 3 options & have the program generate an error message if incorrect data is entered by the user. Below is my code. I keep getting an error back stating that there is a syntax error on token else. Any help is appreciated. Thanks.
This is what I have so far. If I remove the else statements, the program runs, but when you input any letter for the medium, the program terminates.
Code:
import java.util.Scanner; //import the Scanner class
class Wave
{
public static void main (String[] args)
{
double distance; //distance variable
double time; //time variable
String medium;
char Air = 'a';
char Water = 'w';
char Steel = 's';
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Sound Wave Calculator\n");
System.out.println("Select the medium the sound wave will travel through.");
System.out.println(" A Air");
System.out.println(" W Water");
System.out.println(" S Steel");
medium = in.next();
Air = medium.charAt(0);
Water = medium.charAt(0);
Steel = medium.charAt(0);
System.out.println("How far will the sound travel (in feet)?");
distance = in.nextDouble();
char response1 = 0;
if ((response1 == 'a') || (response1 == 'A')) //control condition
{
time = distance/1100;
System.out.print("The sound wave will travel" + time + "seconds");
medium = in.next();
response1 = medium.charAt(0); //response is the first letter
}
char response2 = 0;
else if ((response2 == 'w') || (response2 == 'W')) //control condition
{
time = distance/4900;
System.out.print("The sound wave will travel" + time + "seconds");
medium = in.next();
response2 = medium.charAt(0);
}
char response3 = 0;
else if ((response3 == 's') || (response3 == 'S'))
{
time = distance/16400;
System.out.print("The sound wave will travel" + time + "seconds");
medium = in.next();
response3 = medium.charAt(0);
}
else if (medium != 'a' && medium != 'w' && medium != 's')
{
System.out.println("Illegal entry. Aborting Program.");
System.out.println("Goodbye.");
}
System.out.println("Goodbye"); //end of main
}
}