Without using a "dateformat" or something along those lines, I am trying to change a string of US date "mm/dd/yyyy" to an EU format "dd/mm/yyyy". I am to do this using strings and string methods. I feel like I am very close to this but cannot quite figure it out. This is my code:
import java.util.Scanner;
public class DateChange {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String usDate, euDate, day, month;
int year;
System.out.println("Enter a date in the form month/day/year:");
usDate = kbd.nextLine();
month = usDate.substring(0, '/');
day = usDate.substring('/', '/');
year = usDate.lastIndexOf('/');
euDate = day + "." + month + "." + year;
System.out.println("Your date in European form is:");
System.out.println(euDate);
}
}
This is the error I am getting:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 47
at java.lang.String.substring(String.java:1963)
at DateChange.main(DateChange.java:12)
Why not split the input string using '/' as separator using the method String.split
. It returns an array of strings. Just swap the first two elements of the array.
String usdate = "12/27/2015";
String[] arr = usdate.split("/");
String eudate = arr[1] + "/" + arr[0] + "/" + arr[2];
The problem is that java.String.substring takes two int values, not char values. The int value of ' / ' is 47, so substring is taking 47 as an input, not the indexOf ' / '.
If you want to solve this without using the java library, use the following code:
import java.util.*;
public class DateChange {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String usDate, euDate, day = "", month = "", year = "";
System.out.println("Enter a date in the form month/day/year:");
usDate = kbd.nextLine();
kbd.close();
month = usDate.substring(0, usDate.indexOf("/"));
day = usDate.substring(usDate.indexOf("/")+1, usDate.lastIndexOf("/"));
year = usDate.substring(usDate.lastIndexOf("/")+1, usDate.length());
euDate = day + "." + month + "." + year;
System.out.println("Your date in European form is:");
System.out.println(euDate);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With