为什么输出是"空"(null)

wisjeremy 2006-08-22 11:01:21
编写一个输出本地IP的方法,源码入下:
import java.net.*;

public class TestIP
{
public static void main(String args[])
{
InetAddress ia = null;
String s = null;

try
{
s = ia.getHostAddress();
}
catch(Exception e)
{

}
System.out.println(s);
}
}

可输出结果是null.为什么?
...全文
145 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
千里冰封820 2006-08-22
  • 打赏
  • 举报
回复
ia是null 的,当然是空了,怎么可能用null去调用它的方法呢
lookhang 2006-08-22
  • 打赏
  • 举报
回复
只需要改一个地方:s = ia.getLocalHost().getHostAddress();
fishyqd 2006-08-22
  • 打赏
  • 举报
回复
import java.net.InetAddress;
import java.net.UnknownHostException;

public class CSDN5
{
public static void main(String args[])
{
InetAddress ia = null;
try {
ia=InetAddress.getLocalHost();
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
String s = null;

try
{
s = ia.getHostAddress();
}
catch(Exception e)
{

}
System.out.println(s);
}
}
fredonline 2006-08-22
  • 打赏
  • 举报
回复
你的ia对象本身就是个空,不能从中获得IP地址的。
waterborn 2006-08-22
  • 打赏
  • 举报
回复
InetAddress ia = InetAddress.getLocalHost();;
String s = null;

try {
s = ia.getHostAddress();
} catch (Exception e) {

}
System.out.println(s);

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧