Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Whitespace split issue, java

beginner here I have searched anywhere but I can’t seem to find any solution or problems related to mine. I’ve just started learning java and Here is my problem:

I have a working code where the input is split by "/":

Scanner d = new Scanner(System.in);
System.out.println("Enter your birthday (mm/dd/yyyy): ");
String birthday = d.next();

String[] bdayArr = birthday.split("/", 3);

int current = 2022;
int age = current - Integer.parseInt(bdayArr[2]);

now it was just a solution for the meantime as the date format I want to needs to be seperated with spaces (ex, January 21, 1899)
and the purpose of me splitting is i need to get the year to use in a code block that computes the age of the person based on the birth year.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, when i try to split it by whitespace I can’t seem to access the array anymore. Error codes ranging from out of bounds to a NumberFormatException when i input (ex: January 21, 1989) (code below)

String[] bdayArr = birthday.split("\\s+", 3);

I don’t know what i’m doing wrong, hopefully someone can help. (I know the question is too long and not straight to the point I wanted to provide as much context)

>Solution :

The problem is caused by d.next(), you should use d.nextLine() insted.
to understand why you should check this quesiton What's the difference between next() and nextLine() methods from Scanner class?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading