我试图通过传递主机名来获取主机地址。但是在运行我的代码时,我得到了例外:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at socketprogram_client.SocketProgram_Client.main(SocketProgram_Client.java:16)
Java Result: 1
有人可以告诉我为什么会收到此错误吗?
这是我的代码:
package socketprogram_client;
import java.io.*;
import java.net.*;
public class SocketProgram_Client
{
public static void main ( String args[] ) throws IOException
{
String host_name = args[0];
try
{
InetAddress my_ipaddr = InetAddress.getByName(host_name);
System.out.println("Resolved to IP address: " + my_ipaddr.getHostAddress());
}
catch ( UnknownHostException e )
{
System.out.println("Could not find IP address for: " + host_name);
}
}
}
答案 0 :(得分:2)
看来你没有传递任何论据。你应该做一些检查:
public static void main ( String args[] ) throws IOException
{
if(args == null || args.length == 0){
System.out.println("You didn't pass in any arguments!");
}
else{
//rest of code
}
}
运行程序时,必须在命令行中有一个参数:
java SocketProgram_Client the_argument
the_argument
是您传入的参数(args[0]
)。
答案 1 :(得分:-1)
您可能没有将参数传递给args
,因此args[0]
可能为空。
package socketprogram_client;
import java.io.*;
import java.net.*;
public class SocketProgram_Client
{
public static void main ( String args[] ) throws IOException
{
if(args.length == 0){
System.out.println("You didn't say a host name");
System.exit(1);
}
String host_name = args[0];
try
{
InetAddress my_ipaddr = InetAddress.getByName(host_name);
System.out.println("Resolved to IP address: " + my_ipaddr.getHostAddress());
}
catch ( UnknownHostException e )
{
System.out.println("Could not find IP address for: " + host_name);
}
}
}