gpt4 book ai didi

java - 如何创建 INetAddress 构造函数

转载 作者:行者123 更新时间:2023-12-01 11:00:04 24 4
gpt4 key购买 nike

我有这个代码:

  import java.net.InetAddress;
import java.net.UnknownHostException;

public class NsLookup {

private InetAddress inet = null;

public void resolve(String host) {
try {
inet = InetAddress.getByName(host);

System.out.println("Host name : " + inet.getHostName());
System.out.println("IP Address: " + inet.getHostAddress());
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
NsLookup lookup = new NsLookup();
lookup.resolve(args[0]);
}
}

但是我试图向初始化 InetAddress 对象的类添加一个构造函数,将其与 resolve() 方法分开,但不清楚如何操作,有什么建议吗?

最佳答案

您需要的是一个简单的构造函数,它接受字符串形式的主机名并为其初始化 InetAddress 对象,这可以轻松完成,如下所示:

  import java.net.InetAddress;
import java.net.UnknownHostException;

public class NsLookup {

private InetAddress inet = null;

// you need to define this extra constructor
public NsLookup(String host){
try{
inet = InetAddress.getByName(host);
}
catch(UnknownHostException uhe){
uhe.printStackTrace();
}
}
// constructor ends here

// Also you don't need to remove the argument received by the resolve()
// so that one could resolve other hostnames too.

public void resolve(String host) {
try {
inet = InetAddress.getByName(host);
System.out.println("Host name : " + inet.getHostName());
System.out.println("IP Address: " + inet.getHostAddress());
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
NsLookup nsl = new NsLookup("YOUR-HOSTNAME");
// add your rest code here
}
}

关于java - 如何创建 INetAddress 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33418310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com