Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whitespace split issue, java

Tags:

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.

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)

like image 759
Wazu Wazu Avatar asked Nov 17 '25 13:11

Wazu Wazu


1 Answers

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?

like image 64
Daniel Botnik Avatar answered Nov 19 '25 03:11

Daniel Botnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!