【发布时间】:2019-10-08 09:47:56
【问题描述】:
对于我的家庭作业,我需要在 Java 中合并两个对象。我必须创建一个方法
void mergeTrains(Train other) 这会将来自另一列火车的所有机车和汽车添加到当前火车。因此,在调用train1.mergeTrains(train2) 之后,参数 train 将在完成后没有汽车和机车。它们都将被添加到 train1。
然后我们必须使用 JUnit 来检查数组和机车是否正确合并。 这是我目前所拥有的:
public class Train {
// data members
private String trainName;
private int numOfLocomotives;
private int[] freightCars;
// constructor
public Train (String trainName, int numOfLocomotives) {
this.trainName = trainName;
this.numOfLocomotives = numOfLocomotives;
}
public int getNumOfLocomotives() {
return numOfLocomotives;
}
public void setNumOfLocomotives(int numOfLocomotives) {
if (numOfLocomotives < 0) {
System.out.println("Error. Locomotives can't be set to less than 0.");
return;
} else {
this.numOfLocomotives = numOfLocomotives;
}
}
public int[] getFreightCars(int... freightCars) {
if (freightCars == null) {
System.out.println("There are no freight cars in the list.");
return freightCars;
} else {
return freightCars;
}
}
public int[] removeAllCars(int...freightCars) {
freightCars = null;
return freightCars;
}
public int[] addCars(int...weights) {
int count = 0;
int[] freightCars = {10, 20, 30}; // used to check if method functions correctly
int[] newTrain = new int[freightCars.length + weights.length];
for (int i = 0; i < freightCars.length; i++) {
newTrain[i] = freightCars[i];
count++;
}
for (int j = 0; j < weights.length; j++) {
newTrain[count++] = weights[j];
}
for (int i = 0; i < newTrain.length; i++) {
System.out.print(newTrain[i] + " ");
}
return newTrain;
}
public void mergeTrains(Train other) {
this.numOfLocomotives = this.numOfLocomotives + other.numOfLocomotives;
other.numOfLocomotives = 0;
}
这是我的 JUnit 测试类:
class TestTrain {
int[] train1Cars = {10, 20, 30};
int[] train2Cars = {4, 11, 15};
int[] mergedTrain = {10, 20, 30, 4, 11, 15};
@Test
void testRemoveCars() {
Train t1 = new Train("Thomas", 2);
assertArrayEquals(t1.removeAllCars(train1Cars), null);
}
@Test
void testAddCars() {
Train t1 = new Train ("Thomas", 2);
assertArrayEquals(t1.addCars(train2Cars), mergedTrain);
}
@Test
void testMergeTrains() {
Train t1 = new Train ("Thomas", 1);
Train other = new Train ("Rob", 4);
}
}
基本上我需要弄清楚我应该如何处理Train other 参数。然后我如何使用 JUnit 进行测试。我认为在 mergeTrains 方法中更改机车是正确的,但我也不知道如何在 JUnit 中进行检查。
【问题讨论】: