错误:java.lang.ArrayIndexOutOfBoundsException:1,如何处理

时间:2015-04-23 21:37:07

标签: java indexoutofboundsexception

如何处理此代码中发出此消息的错误 java.lang.ArrayIndexOutOfBoundsException:1

使用udp socket

将数据包从客户端发送到服务器
    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..." ) ;



  }
   }

2 个答案:

答案 0 :(得分:2)

数组元素从索引零开始,而不是1

int port = Integer.parseInt( args[0] ) ;  // first argument is args[0]

答案 1 :(得分:0)

更改if语句以检查等号,即

if( args.length == 0 )

或使用1代替0,即

if( args.length != 1 )

当前代码表示仅当Integer.parseInt()的长度为args时才会出现0语句,因此通过寻址args[0]您尝试索引第一个位置一个空数组。