Hi,
Im new to java and was wondering if someone could help me with my problem.
Im writing a program which will calculate how long a journey will take, the user will need to enter a character to represent what type of road/speed they are doing and how long the journey is.
This is the road/speed details:-
If they type “m” they are on a (motorway) travelling 85 kph
“a” (A road) 70 kph
“ b” (B road) 55 kph
“u” (urban) 40 kph
I need to declare the speeds as a constant. Read the character inputted and use a "switch" statement to set the speed accordingly to above.
So far I can’t get the “switch” statement to work correctly, here is my code:-
public class Travel {
public static void main(String[] argv)
{
double traveldistance, time;
int convertseconds, hours, remainder, minutes, seconds;
char roadtype;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
System.out.println ("Type the road type:"); // Prompts to enter travel distance and reads the values
roadtype = UserInput.readChar();
switch (roadtype){
case 'm': // Motorway
double m=85;
break;
case 'a': // A Road
double a=70;
break;
case 'b': // B Road
double b=55;
break;
case 'u': // Urban Road
double u=40;
break;
default:
System.out.println("Invalid road type " + roadtype); // Invalid road type
System.exit(0);
break;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
System.out.println ("Type the travel distance:"); // Prompts to enter travel distance and reads the values
traveldistance = UserInput.readDouble();
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
time = traveldistance / roadtype; // formula (units in hours)
convertseconds = (int)((time * 60) * 60); // converts hours to seconds
hours = convertseconds / 3600; // converts the seconds to HH:MM:SS
remainder = convertseconds % 3600;
minutes = remainder / 60;
seconds = remainder % 60;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
System.out.println ("To travel " + traveldistance + " takes " + convertseconds + " seconds");
System.out.println ("To travel " + traveldistance + " takes " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
} // end of main
} // end class
The data I need to enter is:-
Type the road type: m
Type the travel distance: 1234
The output should be:-
To travel 1234.0 road type m takes 52263 seconds
To travel 1234.0 road type m takes 14 hours 31 minutes 3 seconds
When I try my program I get:-
To travel 1234.0 takes 40755 seconds
To travel 1234.0 takes 11 hours 19 minutes 15 seconds
I can’t seem to understand what the problem is ( I think its the switch statement).
Any help is much appreciated .
Hope i havent confused you :confused:
Thanks