How take date as an input from users by using scanner class in Java? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

How take date as an input from users by using scanner class in Java?

i want it to make the user input their birthday and it'll display the date in the cmd

18th Sep 2019, 4:05 PM
Pavanithan
Pavanithan - avatar
9 ответов
+ 3
You just do the same thing as you would with the name 🤷‍♂️ Scanner in = new Scanner(System.in); System.out.print("Enter your birthday (dd/mm/yyyy) >>> "); String birthDate = in.nextLine();
18th Sep 2019, 4:18 PM
Faisal
Faisal - avatar
+ 4
In what format do you want the date? Thinking of some ideas, you could set up different variables to be for the birth date, month, and year, and ask for input separately for each one, or you could ask for the user to input their birthday in some format along the lines of dd/mm/yyyy and just read the data from that string
18th Sep 2019, 4:07 PM
Faisal
Faisal - avatar
+ 2
if(!input.matches("\\d{1,2}/\\d{1,2}/\\d{4}"){ //redo input } you can use do while
18th Sep 2019, 4:36 PM
Taste
Taste - avatar
+ 1
input matches will take a regex pattern, and check if the string match with it. \\d means a number {1,2} means 1 to 2 digit so \\d{1,2} means 1 or 2 digit of number / is your date separator and lastly \\d{4} means exactly 4 digit of number
19th Sep 2019, 5:00 AM
Taste
Taste - avatar
0
@Faisal i prefer if dd/mm/yy, but how to set it, so that the scanner can accept the date as an input?. For example if we want the user to input name, we do something like, String name; Scanner sc = new Scanner(); System.out.println("enter your name"); name = sc.nextLine(); how to set it to date? System.out.println(name);
18th Sep 2019, 4:16 PM
Pavanithan
Pavanithan - avatar
0
i'll try and i'll update the results. Thank you Faisal
18th Sep 2019, 4:20 PM
Pavanithan
Pavanithan - avatar
0
@Faisal it works, but what if the user inputs the birth date in the wrong format. For example instead of going 22/10/2018, the user input 22 October 2018. is there any way to catch the Exception?
18th Sep 2019, 4:27 PM
Pavanithan
Pavanithan - avatar
0
@Taste can you please explain the code that you gave ?
19th Sep 2019, 1:10 AM
Pavanithan
Pavanithan - avatar
0
import java.util.scanner; public static void main(String args){ // if you want string input Scanner in = new Scanner(System.in); System.out.print("Enter your birthday (dd/mm/yyyy) >>> "); String birthDate = in.nextLine(); // if you want double Scanner in = new Scanner(System.in); System.out.print("Enter price "); double birthDate = in.nextDouble(); //so on } Scanner in = new Scanner(System.in); System.out.print("Enter your birthday (dd/mm/yyyy) >>> "); String birthDate = in.nextLine();
10th Feb 2024, 2:41 PM
Siddharth Shivwanshi
Siddharth Shivwanshi - avatar