因此将IPv4字符串传递给isValidElement
public static boolean isValidElement(String token) {
String[] validString = token.split("\\.");
if (validString.length != 4)
return false;
for (String str: validString ) {
try{
int i = Integer.parseInt(str);
if ((i < 0) || (i > 255)) {
return false;
}
}
catch(NumberFormatException ex){
return false;
}
}
return true;
}
这一切都很好,但是当该字符串传递给将字符串存储到数组中的方法时,它会起作用。
public void setParts(String ip) {
parts = new int[4];
if (!isValidElement(ip))
for(int i = 0; i <= parts.length; i++)
parts[i] = 0;
else
try {
String[] ipArr = ip.split("\\.");
for (int i = 0; i < ipArr.length; i++) {
parts[i] = Integer.parseInt(ipArr[i]);
}
}
catch (NumberFormatException e) {
parts = new int[4];
}
}
我哪里出错了/我错过了什么?
我有一个JUnit测试
public void testSetPartsString() {
correct1.setParts("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]);
但它停止在
工作assertEquals(4, a.length);
我没有正确重置实例阵列部件吗?
答案 0 :(得分:0)
以下代码可以正常使用。
public class AssertionCheck {
public static void main(String[] args) {
String ip="12.14.16.18";
int[] parts = new int[4];
if(!(isValidElement(ip)))
for(int i = 0; i<=parts.length; i++)
parts[i] = 0;
else{
String[] ipArr = ip.split("\\.");
Assert.assertEquals(4, ipArr.length);
Assert.assertEquals(12, Integer.parseInt(ipArr[0]));
Assert.assertEquals(14, Integer.parseInt(ipArr[1]));
Assert.assertEquals(16, Integer.parseInt(ipArr[2]));
Assert.assertEquals(18, Integer.parseInt(ipArr[3]));
System.out.println("Assertion completed Successfully");
}
}
public static boolean isValidElement(String token) {
String[] validString = token.split("\\.");
if (validString.length != 4)
return false;
for (String str: validString ) {
try{
int i = Integer.parseInt(str);
if ((i < 0) || (i > 255)) {
return false;
}
}
catch(NumberFormatException ex){
return false;
}
}
return true;
}
}