Java – Calculate Taxi Fares
Posted Dec 2nd, 2009 by Conor in in College,Java,LanguagesThis week my ICSP assignment was to calculate taxi fares. The task was:
Using the fare table write a program that calculates the fares and test if it is correct. Upload your .java or your Scratch file. A template file for java will be provided. (Hint, only the boundary values needs to be tested. The fare table is also presented in the slides. The compile command for java should be “javac TaxiRide.java”)
Fare table Distance (km) Cost (€) >50 30 50-100 25, plus 9 for each km > 50 100 – 2000 190, plus 8 for each km > 100 > 2000 1800
It wasn’t the hardest task. The only thing that confused me was the Java switch syntax. In PHP you can have conditions in a switch statement such as:
<?php
switch($num){
case ($num<10):
// blah
break;
case ($num<100):
// blah
break;
default:
//blah
?>
I couldn’t get Java to accept anything other than a value for the variable bring switched. So I did it the old-fashioned way! My code is below…
public class TaxiRide{
public int distance=0;
public TaxiRide(String arg){
try{
int distance=Integer.parseInt(arg);
this.distance=distance;
}
catch(NumberFormatException e){
System.err.println("Arguement must be an integer representing the distance traveled");
System.exit(1);
}
}
public int calculateFare(){
int distance=this.distance;
int fare=0;
int i=0;
if(distance<50){
return 30;
}
if(distance%lt;100){
fare=25;
distance-=50;
for(i=0;i<distance;i++){
fare+=9;
}
return fare;
}
if(distance<2000){
fare=190;
distance-=100;
for(i=0;i<distance;i++){
fare+=8;
}
return fare;
}
return 1800;
}
public static void main(String[] args){
TaxiRide taxiRide = new TaxiRide(args[0]);
int fare=taxiRide.calculateFare();
System.out.println("The fare is: "+fare+" euro for traveling "+taxiRide.distance+"kM\n Thank you\n");
}
}
I feel i am learning a lot from this course. Lately I have been experimenting in a few different languages. I added a bit to the Scratch Linux installer, written in Perl, so that it added an icon in the applications menu during installation. I’ve also been messing around with bash, trying to automate some of my most common commands… was thinking of writing a small bash script that backed up my data when my external hard drive is plugged in, similar to Time Machine on OSX.