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
9 Answers
+ 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();
+ 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
+ 2
if(!input.matches("\\d{1,2}/\\d{1,2}/\\d{4}"){
//redo input
}
you can use do while
+ 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
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);
0
i'll try and i'll update the results. Thank you Faisal
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?
0
@Taste can you please explain the code that you gave ?
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();