reading user input of class 'Date'

ppc :

Hello I am new to JAVA and I have been searching the net for this and I couldn't find a solution.

So I am trying to read user input and store them in vector but one of them includes a Date input. Now, I created a class of name 'Date' so I have to use Date as the type, however i don't know what to put as nextLine or NextInt - in order to read.

public static void edit(){
      viewAll();
      Scanner in = new Scanner (System.in);
      int i;


      System.out.println("Enter the Animal Code you wish to edit:");
      String cd = in.nextLine();

      if (cd == code){

       System.out.print("What is the animal's type? "); 
        String type2 = in.nextLine();
        n.add(type2);

       System.out.print("Enter the animal's unique code - Format: (XXXX111)");
       String code2 = in.nextLine();
       n.add(code2);
       //unique
       //XXXX102
       System.out.print("Enter the animal's weight:" ); 
       int weight2 = in.nextInt();
       n.add(weight2);

       System.out.print("Enter the date that the animal was obtained on: (dd/mm/yyyy)");
       Date date2 = in.next();

       list.addAll(n);

       //use date class
       System.out.print("Enter the animal's room and section (location) in the park:");
       String location2 = in.nextLine();
       n.add(location2);



       System.out.println();
       System.out.println("Changes have been saved");
       System.out.println();

     }
Nexevis :

First import the libraries you need including date with:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

You can then take in the input as a String and convert it to Date by doing:

    DateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");
    String dateString = in.nextLine();
    Date animalDate = formatter.parse(dateString);

You will not need to create a Date class and can just the java.util library.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116427&siteId=1