user3496026
user3496026

Reputation: 59

java.lang.ArrayIndexOutOfBoundsException: 2 error message

I am writing some code trying to split a string (01/04/2010) into 3 different integers. When I try to run it, I get an ArrayIndexOutOfBoundsException error.

Here is the code:

public Date(String date) {

    String dayz[];
    dayz = date.split("/");

    int m=Integer.parseInt(dayz[0]);
    int d=Integer.parseInt(dayz[1]);
    int y=Integer.parseInt(dayz[2]);
    if(y<100) { 
        y=Integer.parseInt(dayz[2])+2000;
    }

    setComponents(m,d,y);


}

Here is the setComponents method:

 public void setComponents(int month, int day, int year) {

    if (month < 1 || month > 12 || year < MIN_YEAR || day < 1 || day >     numDaysInMonth(month, year)) {
        throw new IllegalArgumentException();
    }
    this.month = month;
    this.day = day;
    this.year = year;

}

Any help?

Upvotes: 0

Views: 617

Answers (2)

Harry
Harry

Reputation: 1472

Based on your comment: oh I just realized that I am supposed to check for 04/10, which should not work and it supposed to print out a message. Maybe that's what is wrong. Any idea for how to improve the code?

public Date(String date) {

  String dayz[];
  dayz = date.split("/");

  if(days.length < 3)
  {
    System.err.println("Invalid date: " + date + ". It should be in the format 'DD/MM/YYYY.");
  }
  else
  {
    int m=Integer.parseInt(dayz[0]);
    int d=Integer.parseInt(dayz[1]);
    int y=Integer.parseInt(dayz[2]);
    if(y<100) { 
      y=Integer.parseInt(dayz[2])+2000;
    }
    setComponents(m,d,y);
  }
}

Upvotes: 0

necromancer
necromancer

Reputation: 33

You can use StringTokenizer. Its much cleaner and simple to use.

import java.util.StringTokenizer;

public class HelloWorld{
    public static void main(String []args){
        String a="01/04/2010";
        StringTokenizer st= new StringTokenizer(a,"/");
        int data[] = new int[3];
        int count =0;
        while(st.hasMoreElements())
        {
            data[count++]=Integer.parseInt(st.nextToken());
        }

        for(int i=0;i<3;i++)
            System.out.println(data[i]);
    }
}

Upvotes: 1

Related Questions