我有3节课。我正在学习接口和接口类 TravelCost 必须具有公共抽象以及方法类型和名称,以便它在所有三个类中都是一致的。这三个类(AirTravelCost、TrainTravelCost、CarTravelCost)将实现 TravelCost。我已经完成了所有设置并经过测试可以正常工作。但是,我假设的测试页面是您通过 arrayList 输入搜索以获取最低成本和最短持续时间的地方。我不知道该怎么做,因为我以前从未在 ArrayList 中这样做过。这里是测试类中的示例代码:
import java.util.*;
public class TestTravelCost
{
public static void main(String [] args)
{
/*Scanner scn = new Scanner(System.in); //scanner object
System.out.println("Number of Miles: ");
double numOfMiles = scn.nextDouble();
System.out.println("Hotel cost per night: ");
double cost = scn.nextDouble();
System.out.println("Description: ");
String description = scn.nextLine();*/
TravelCost c = new CarTravelCost(400, 200, "Boston");//instantiate object for car travel
TravelCost t = new TrainTravelCost(6, 60.0, "Boston"); //instantiate object for train travel
TravelCost a = new AirTravelCost(224, "20110103", "0743" , "20110103", "1153", "Boston");//instantiate object for air travel
ArrayList<TravelCost> AL = new ArrayList<TravelCost>();//array list for car travel
AL.add(c);
AL.add(t);
AL.add(a);
for(TravelCost tc : AL)
{
System.out.println(tc.toString());
}
}
}
输出:到波士顿的汽车旅行需要 7.2727272727272725 小时和成本 210.0
到波士顿的火车旅行需要 6.0 小时和成本 70.0
到波士顿的航空旅行需要 1.0166666666666666 和成本 243.48888888888888 //这不是正确的计算,我不知道我在哪里'错了,但它假设与最短持续时间相同。我想我不擅长数学。
这是我用于航空旅行的计算方法
public double getDuration()
{
//---DEPARTURE---//
int Dyear = Integer.parseInt(departureDate.substring(0,3)); //2011
int Dmonth = Integer.parseInt(departureDate.substring(4,5));//01
int Dday = Integer.parseInt(departureDate.substring(6,7));//03
int Dhour = Integer.parseInt(departureTime.substring(0,1));//0743
int Dminute = Integer.parseInt(departureTime.substring(2,3));//1153
//---ARRIVAL---//
int Ayear = Integer.parseInt(arrivalDate.substring(0,3)); //2011
int Amonth = Integer.parseInt(arrivalDate.substring(4,5));//01
int Aday = Integer.parseInt(arrivalDate.substring(6,7));//03
int Ahour = Integer.parseInt(arrivalTime.substring(0,1));//0743
int Aminute = Integer.parseInt(arrivalTime.substring(2,3));//1153
GregorianCalendar date = new GregorianCalendar(Dyear, Dmonth, Dday, Dhour, Dminute);//departure date & time
GregorianCalendar time = new GregorianCalendar(Ayear, Amonth, Aday, Ahour, Aminute);//arrival date & time
//date = arrivalDate - departureDate;//2011-01-03 - 2011-01-03 = 0
//time = arrivalTime - departureTime;//0734 - 1153 = 410
double duration = (Math.abs(date.getTimeInMillis() - time.getTimeInMillis()) / 60000.0) / 60.0;
return duration;
`enter code here` }
如何在我的代码中得到这个结果?
最低成本:到波士顿的火车旅行需要 11.0 小时,费用为 70.0最短时间
:到波士顿的航空旅行需要 4.166666666666667 小时,费用为 234.0