简体   繁体   中英

Receiving an error while executing method substring in Java

I have to do a String exercise where I have to enter a date like dd/mm/yyyy. Everything works fine except if I enter a space as the input, it prints this error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 2, length 1
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3720)
    at java.base/java.lang.String.substring(String.java:1909)
    at ex5.main(ex5.java:17)

This is my code:

import cs1.*;
public class ex5
{
   public static void main(String[] args) 
   {
      String data = "18/08/2011";



      //asking for the data
      System.out.printf("DATA: ");
      data = Keyboard.readString();



      //system.out
      System.out.printf("DIA: %s %n", data.substring(0, 2));
      System.out.printf("MES: %s %n", data.substring(3, 5));
      System.out.printf("ANY: %s", data.substring(6, 10)); 
   }
}

I have to do a String exercise where I have to enter a date like dd/mm/yyyy. Everything works fine except if I enter a space as the input, it prints this error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 2, length 1
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3720)
    at java.base/java.lang.String.substring(String.java:1909)
    at ex5.main(ex5.java:17)

This is my code:

import cs1.*;
public class ex5
{
   public static void main(String[] args) 
   {
      String data = "18/08/2011";



      //asking for the data
      System.out.printf("DATA: ");
      data = Keyboard.readString();



      //system.out
      System.out.printf("DIA: %s %n", data.substring(0, 2));
      System.out.printf("MES: %s %n", data.substring(3, 5));
      System.out.printf("ANY: %s", data.substring(6, 10)); 
   }
}

I have to do a String exercise where I have to enter a date like dd/mm/yyyy. Everything works fine except if I enter a space as the input, it prints this error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 2, length 1
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3720)
    at java.base/java.lang.String.substring(String.java:1909)
    at ex5.main(ex5.java:17)

This is my code:

import cs1.*;
public class ex5
{
   public static void main(String[] args) 
   {
      String data = "18/08/2011";



      //asking for the data
      System.out.printf("DATA: ");
      data = Keyboard.readString();



      //system.out
      System.out.printf("DIA: %s %n", data.substring(0, 2));
      System.out.printf("MES: %s %n", data.substring(3, 5));
      System.out.printf("ANY: %s", data.substring(6, 10)); 
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM