Error: java.lang.ArrayIndexOutOfBoundsException: 1, how can be handled
Error: java.lang.ArrayIndexOutOfBoundsException: 1, how can be handled
如何处理代码中发出此消息的错误
java.lang.ArrayIndexOutOfBoundsException: 1
为了使用 udp 套接字将数据包从客户端发送到服务器
public class DatagramServer
{
private final static int PACKETSIZE = 100 ;
public static void main( String args[] )
{
// Check the arguments
if( args.length != 0 )
{
System.out.println( "usage: DatagramServer port" ) ;
return ;
}
try
{
// Convert the argument to ensure that is it valid
int port = Integer.parseInt( args[1] ) ;
// Construct the socket
DatagramSocket socket = new DatagramSocket( port ) ;
System.out.println( "The server is ready..." ) ;
}
}
数组元素从索引零开始,而不是 1
:
int port = Integer.parseInt( args[0] ) ; // first argument is args[0]
更改 if
语句以检查是否相等,即
if( args.length == 0 )
或使用1
代替0
,即
if( args.length != 1 )
当前代码意味着只有当 args
的长度为 0
时才会到达 Integer.parseInt()
语句,因此通过寻址 args[0]
您试图索引空数组的第一个位置。
如何处理代码中发出此消息的错误 java.lang.ArrayIndexOutOfBoundsException: 1
为了使用 udp 套接字将数据包从客户端发送到服务器
public class DatagramServer
{
private final static int PACKETSIZE = 100 ;
public static void main( String args[] )
{
// Check the arguments
if( args.length != 0 )
{
System.out.println( "usage: DatagramServer port" ) ;
return ;
}
try
{
// Convert the argument to ensure that is it valid
int port = Integer.parseInt( args[1] ) ;
// Construct the socket
DatagramSocket socket = new DatagramSocket( port ) ;
System.out.println( "The server is ready..." ) ;
}
}
数组元素从索引零开始,而不是 1
:
int port = Integer.parseInt( args[0] ) ; // first argument is args[0]
更改 if
语句以检查是否相等,即
if( args.length == 0 )
或使用1
代替0
,即
if( args.length != 1 )
当前代码意味着只有当 args
的长度为 0
时才会到达 Integer.parseInt()
语句,因此通过寻址 args[0]
您试图索引空数组的第一个位置。