在 Java 中使用同一类的另一个方法中的方法
我有一个类 IPAddressString
,它具有:
- 一个
String
类型的private
字段,称为ipAddress
- 一个
public< /code> 方法
getOctet
带有单个参数int index
,返回一个int
。返回值是根据ipAddress
和index
计算的, public
方法isPrivateNetwork
返回一个boolean< /code> 基于
getOctet
的返回值
所以这是代码:
public class IPAddressString {
private String ipAddress;
public IPAddressString(int num1, int num2, int num3, int num4) {
this.ipAddress = num1 + "." + num2 + "." + num3 + "." + num4;
}
public String toString() {
return this.IpAdress;
}
public boolean equals(IPAddressString other) {
return ((other.toString()).equals(ipAddress));
}
public int getOctet(int index) {
StringBuffer buf = new StringBuffer();
int point = index;
int countPoints = 0;
for (int i = 0; i <= ipAddress.length() - 1; i++) {
if ((ipAddress.charAt(i)) == '.') {
countPoints++;
}
if ((countPoints == point) && ipAddress.charAt(i) != '.') {
buf.append(ipAddress.charAt(i));
}
}
String result = buf.toString();
return Integer.parseInt(result);
}
public boolean isPrivateNetwork(){
// I want to use getOctet here
}
}
我想在 isPrivateNetwork
中做的事情类似于 ipAddress.getOctet(someIndex)
,这是不可能的,因为 ipAddress
是 String
而不是 IPAddressString
。那么,我应该在 IPAddressString
的哪个实例上调用 isPrivateNetwork
?
I have a class IPAddressString
that has:
- a
private
field of typeString
calledipAddress
- a
public
methodgetOctet
with a single argumentint index
that returns anint
. The return value is computed based onipAddress
andindex
- a
public
methodisPrivateNetwork
that returns aboolean
based on the return value ofgetOctet
So this is the code:
public class IPAddressString {
private String ipAddress;
public IPAddressString(int num1, int num2, int num3, int num4) {
this.ipAddress = num1 + "." + num2 + "." + num3 + "." + num4;
}
public String toString() {
return this.IpAdress;
}
public boolean equals(IPAddressString other) {
return ((other.toString()).equals(ipAddress));
}
public int getOctet(int index) {
StringBuffer buf = new StringBuffer();
int point = index;
int countPoints = 0;
for (int i = 0; i <= ipAddress.length() - 1; i++) {
if ((ipAddress.charAt(i)) == '.') {
countPoints++;
}
if ((countPoints == point) && ipAddress.charAt(i) != '.') {
buf.append(ipAddress.charAt(i));
}
}
String result = buf.toString();
return Integer.parseInt(result);
}
public boolean isPrivateNetwork(){
// I want to use getOctet here
}
}
What I would like to do inside isPrivateNetwork
is something like ipAddress.getOctet(someIndex)
, which is not possible because ipAddress
is a String
and not an IPAddressString
. So, on which instance of IPAddressString
am I supposed to call isPrivateNetwork
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么你为什么不直接使用:
So why don't you just use: