Solved: Java -- how to get substring from a string of numbers with spaces
Rank beginner at Java. Need to pull out the month, day, and year separately from an integer. Here's what I have done. It's compiling now (that's an improvement!), but gives me a "String index out of range" error.
Since the spaces are causing trouble, I believe, the error throws on the indicated line -- as soon as the code runs into the first space. How can I do extract this information? The format of the birthdate, with spaces, cannot change.
//Get the date of birth.
System.out.println("Please enter the renter's date of birth (mm dd yyyy): ");
birthMonth = kb.nextInt();
String birthDateString = Integer.toString(birthMonth);
String birthMonthString = birthDateString.substring(0,1); String birthDayString = birthDateString.substring(3,4); //error throws on this line
String birthYearString = birthDateString.substring(6,9);
birthMonth = Integer.parseInt(birthMonthString);
birthDay = Integer.parseInt(birthDayString);
birthYear = Integer.parseInt(birthYearString);
You've marked this solved, but no responses have been given. Can you please confirm that you've found the solution yourself, or else click "mark unsolved" to alert helpers that assistance may still be needed.
Edit: Or, I suppose I could just look at the next thread in the forum and see for myself.
I marked it solved because I solved it. Is that the wrong protocol on this site? My apologies. I wanted to close it out so no one would waste time on it.
Yes, I kept going. Problems I can't solve and programs that don't work are annoying! I can't let them go till I figure it out. (Eventually I did figure this one out. It's done now. Time to go over to the other thread and close that out too, if I didn't already do that last night.)
THIS THREAD HAS EXPIRED.
Are you having the same problem?
We have volunteers ready to answer your question, but first you'll have to join for free. Need help getting started? Check out our Welcome Guide.