返回声明错误 - 解析IP地址字符串
任何人都可以告诉我为什么我的最后一个返回语句不起作用吗?返回声明错误 - 解析IP地址字符串
public class IpAddress
{
private String dottedDecimal;
private int[] Octet= new int[4];
public int i;
//Default constructor
public IpAddress()
{
dottedDecimal = "0.0.0.0";
for (i=0; i<=3; i++)
{
Octet[i] = 0; //setting the array to zero
}
} // end default constructor
//************************************
//Specified constructor
public IpAddress(String myAddress)
{
dottedDecimal = myAddress;
String[] parsedOctets;
parsedOctets = myAddress.split("\\Q.\\E"); // allows to stop at the dot
for (i=0; i <=3; i++)
{
Octet[i] = Integer.parseInt(parsedOctets[i]); // breaking the string down to integers
}
}// end specified constructor
//*****************************************************
public String getDottedDecimal()
{
return dottedDecimal;
}
//*********************
public int getOctet()
{
for (this.i=0; this.i <=3; this.i++)
{
return this.Octet[i];
}
}
} // end ip address class
我想你想要的是最后的方法是这样的:
public int getOctet(int which)
{
if (which >= 0 && which <= 3)
return this.Octet[ which ];
else
return -1; // error. Consider throwing an exception
}
这就是我在找的东西我想我明白你在说什么,你在这个声明中说0到3是可以接受的,因为我只有这个数组中的对象,但是其他的东西都是负数,因为它是错误的。我刚刚了解到这个parseint的东西,以及你们都很棒。 – daddycardona 2009-10-23 01:33:13
看起来像功课给我,但是这显然是行不通的:
public int getOctet()
{
for (this.i=0; this.i <=3; this.i++)
{
return this.Octet[i];
}
}
将从函数的第一个迭代之后返回,你不能从一个函数多次返回。
在某些情况下,如果返回类型是IEnumerable,你可以做一个收益回报 – 2009-10-23 01:33:08
嗯,是的,但这不是这种情况。 – 2009-10-23 03:55:11
对于你的最后一条语句,你正在运行一个什么也不做,只返回一个值的循环。它会在第一次返回,但是循环停止运行,所以其他返回不做任何事情。
public int getOctet()
{
for (this.i=0; this.i <=3; this.i++)
{
return this.Octet[i];
}
}
这相当于:
return this.Octet[0];
因为它只能运行一次。
如果你指的是“获得八位”功能,它仅会返回Octet[0];
return语句停止第一次被击中的函数的执行。你真正想要的是:
public int[] getOctet()
{
return this.Octet;
}
这不起作用我试过我认为这是因为我正在寻找一个数组。哦拉非常好,我很欣赏它。 – daddycardona 2009-10-23 01:34:02
通过命名你的方法getOctect()
,似乎你希望返回数组,不来自数组中的单个int。在这种情况下,您应该将其简化为如下所示:
public int[] getOctet()
{
return this.Octet;
}
你是什么意思“las return statement”?请提供更多详细信息... – 2009-10-23 01:15:29
不要忘记单击复选标记以接受答案... – 2009-10-23 02:29:07
Bob Kaufman已发布解决方案。但我想我会评论一下事情。 “我”不应该是一个实例变量。应该使用实例变量来存储对象的状态。我是一个用于迭代方法的计数器。它与对象本身无关。相反,你应该这样做:“for(int i = 0; i 2009-10-23 12:13:16