因此,会将IPv4数组传递给此方法,如果有效,则在实例变量“parts”中创建该数组的深拷贝。
/**
* If the ip address from the array passed (data) is valid,
* makes a deep copy of the array passed in the instance variable parts.
* For example, if data = {192,168,0,1}, parts should become {192,168,0,1}
* by copying each item of data into corresponding item in parts.
* If the ip address passed is invalid (for example {500,4,60,216}
* or {192,16,01}, or {13,13,13,13,13}, parts should become {0,0,0,0}
*
* remember to reset the instance array parts before you do anything else
* @param data
*/
public void setParts(int[] data) {
this.parts = new int[4];
if (data.length != 4){
parts = new int[]{0,0,0,0};
}
else
for (int i = 0; i <= data.length; i++)
if ((data[i] < 0) || (data[i] > 255))
parts = new int[]{0,0,0,0};
else
parts[i] = data[i];
}
是我到目前为止所拥有的。我可能会缺少什么?
编辑:做了一个简单的更改:
for (int i = 0; i <= data.length; i++)
至
for (int i = 0; i < data.length; i++)
还有一个JUnit测试
public void testSetPartsIntArray() {
correct1.setParts(new int[]{12, 14, 16, 18});
int[] a = correct1.getParts();
assertEquals(4, a.length);
assertEquals(12, a[0]);
assertEquals(14, a[1]);
assertEquals(16, a[2]);
assertEquals(18, a[3]);
correct1.setParts(new int[]{-12, 14, 16, 18});
a = correct1.getParts();
assertEquals(4, a.length);
assertEquals(0, a[0]);
assertEquals(0, a[1]);
assertEquals(0, a[2]);
assertEquals(0, a[3]);
直到作品
assertEquals(0, a[1]);
是什么导致它停在那里?
最佳答案
一旦找到无效值,就必须中断循环:
for (int i = 0; i <= data.length; i++)
if ((data[i] < 0) || (data[i] > 255)) {
parts = new int[]{0,0,0,0};
break;
} else {
parts[i] = data[i];
}
在失败的情况下,第一个元素
-12
无效,因此parts
设置为new int[]{0,0,0,0}
,但是随后您继续循环,并且由于其余数字均有效,因此最终使用{0, 14, 16, 18}
而不是{0, 0, 0, 0}
。