JanusJanus February 2016

Formatting user input in Java to date

I am having some difficulty understanding the way to change a user input of dates an an int to be compared to another int. Am trying to get the user to input his date of birth, then compare it to zodiac signs dates in a switch format if it is possible. Going through most of the post on how to change an input to int, with pars, and SimpleDateFormat I was not able to apply it, as shown in my code when I try to implement "dateOB" that should've been formated to an int, in the switch statement it did not recognize it as so ...

My code so far:

import java.util.*;
import java.text.*;

public class signs {

public static void main(String[] args) {

    Scanner userInput = new Scanner (System.in);

// Intro message
            System.out.println("Hello you, Lets get to know each other");

// User input begin
//name

            String userName;

            System.out.println("What is your name ?");
                userName = userInput.nextLine();

//date of birth


            System.out.println(userName + " please enter you DoB (DD/MM/YYY)");

                String dateOB = userInput.next();
                SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
                try {
                    Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
                    System.out.println(dateOB);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return;
                }

            System.out.println("So your date of birth is " + dateOB);

// choosing zodiac sign
            //starting the switch statement
            int convertedDate = dateOB;
            String zodiacSign;

        switch (convertedDate){

        }


        }
    }

I would appreciate it if someone could explain to me how to implement this in a simple way ...

So i get really great suggestion by you guys, and i ended up with the right understanding of things, just com

Answers


cdaiga February 2016

I think you could get the day and the month of the user's input in "MMdd" format. Then use Integer.parseInt() to get a number, then use if statements to locate the zodiac sign since it is dependent on the day and the month.

For example Aries. Mar 21 - Apr 19. So you can get the input number from the user's date like:

int userVal=0;

if (userDate != null) {
    DateFormat df = new SimpleDateFormat("MMdd");
    userVal = Integer.parseInt(df.format(date));
}

Now you can return aries by doing:

if(userVal >= 321 && userVal <= 419) //Mar 21 == 0321 and April 19 == 0419
   System.out.println("Your zodiac sign: Aries");

Just continue for the other signs.

Implementation

public static void main(String[] args) throws ParseException {
    Date date;
    int mmdd;
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    DateFormat mmDDFormat = new SimpleDateFormat("MMdd");
    Scanner scanner = new Scanner(System.in);

    System.out.println("Please enter your date of birth(dd/MM/yyyy):");
    String stringDate = scanner.next();

    date = dateFormat.parse(stringDate);

    System.out.println("This is your date of birth: " + dateFormat.format(date));

    mmdd = Integer.parseInt(mmDDFormat.format(date));

    System.out.println("This is the mmdd value: " + mmdd);

    //Now getting the Zodiac sign
    System.out.println("The zodiac sign of your date of birth is: ");
    if (mmdd >= 321 && mmdd <= 419) {
        System.out.println("ARIES");
    } else if (mmdd >= 420 && mmdd <= 520) {
        System.out.println("TAURUS");
    } else if (mmdd >= 521 && mmdd <= 620) {
        System.out.println("GEMINI");
    } else if (mmdd >= 621 && mmdd <= 722) {
        System.out.println("CANCER");
    } else if (mmdd >= 723 && mmdd <= 822) {
        System.out.println("LEO");
     


Stefano R. February 2016

I suggest u to use a simple Bean ZodiacSign like that:

class ZodiacSign {
private String  name;
private int     startMonth;
private int     startDay;
private int     endMonth;
private int     ednDay;

public ZodiacSign(String name, int startMonth, int startDay, int endMonth, int ednDay) {
    super();
    this.name = name;
    this.startMonth = startMonth;
    this.startDay = startDay;
    this.endMonth = endMonth;
    this.ednDay = ednDay;
}

// getter & setter

}

and iterate over a collection until you find a match, like this:

List<ZodiacSign> zodiac = Collections.emptyList();
zodiac.add(new ZodiacSign("AQUARIUS", Calendar.JANUARY, 20, Calendar.FEBRUARY, 18));
zodiac.add(new ZodiacSign("PISCES", Calendar.FEBRUARY, 19, Calendar.MARCH, 20));
// ..
zodiac.add(new ZodiacSign("CAPRICORN", Calendar.DECEMBER, 22, Calendar.JANUARY, 19));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
for (ZodiacSign sign : zodiac) {
    if (month >= sign.getStartMonth() && month <= sign.getEndMonth()) {
        if (dayOfMonth >= sign.getStartDay() && dayOfMonth <= sign.getEdnDay()) {
            System.out.println("Zodiac Sign: " + sign.getName());
        }
    }
}


LordAnomander February 2016

Once you have converted the input to a Date you can also get the information by using Calendar.

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH) + 1;

Edit #1:

To get the number you want you have to do an additional calculation, i.e.,

int zodiacNumber = month * 100 + day;

It will result in 1105 for the input 05/11/1984. Vice versa you can use day * 100 + month if you prefer 511.

Or you can parse the date straight to the format you wish by using

int zodiac = Integer.valueOf(new SimpleDateFormat("ddMM").format(date))

which is an even shorter solution.

Edit #2: As you replied to one question with the comment you want a loop to make sure the date is entered in the correct format, do something like this:

boolean correctFormat = false;
do {
   // ask the user for input
   // read the input
   try {
       // try to format the input
       correctFormat = true;
   } catch (ParseException e) {
       correctFormat = false;
   }
} while (!correctFormat);

You can be sure the date was not entered in a correct way if the exception is thrown and thus, by setting the helper variable you can make sure to ask for a date until it is convertable and hence, correct.

Edit #3: You need to use a Date if you are working with SimpleDateFormat not a String.

int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(dateOB));

will not work! You have to use

int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(date));

So your program has to look like this:

Date date = new Date();
String dateOb = "";
boolean correctFormat = false;
do {
    (...)
    date = new  


Dato Mumladze February 2016

You can do it like this

public static void main(String[] args) throws ParseException {

    Scanner userInput = new Scanner(System.in);

    System.out.println("Hello you, Lets get to know each other");

    String userName;

    System.out.println("What is your name ?");
    userName = userInput.nextLine();

    System.out.println(userName + " please enter you DoB (DD/MM/YYY)");

    String dateOB = userInput.next();
    Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
    System.out.println(dateOB);

    System.out.println("So your date of birth is " + dateOB);

    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int day = c.get(Calendar.DAY_OF_YEAR);


    // IF day is from January 20 - to February 18 this means he or she is aquarius
    if (day >= 20 && day <= 49) {
        System.out.println("Aquarius");
    } else if (day >= 50 && day <= 79) {
        //If day if from February 19 to March 20 then pisces
        System.out.println("Pisces");
    }
    //write all zodiac signs ...

    userInput.close();
}


JanusJanus February 2016

Well, finally i was able to get over the problem, with full understanding of new concepts thanks to @LordAnomander for his patience and detailed instructions, @cdaiga insightful alternative solutions and @Dato Mumladze cooperation.

the correct code i reached so far without the zodiac comparison which i will have to apply a switch method, and i am sure since i am still learning it will face some other issue but all good more to learn,

import java.util.*;
import java.text.*;
import java.lang.*;

public class signs {

public static void main(String[] args) throws ParseException {

    Scanner userInput = new Scanner (System.in);

// Intro message
        System.out.println("Hello you, Lets get to know each other");

// User input begin
//name

            String userName;

            System.out.println("What is your name ?");
            userName = userInput.nextLine();

//date of birth
                Date date = new Date();
                String dateOB = "";
            boolean correctFormat = false;      
                do{

                System.out.println(" please enter you DoB (dd/MM/yyyy)");
                dateOB = userInput.next();

                try{
                date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
                    System.out.println("day and month " + dateOB);
                correctFormat = true;
                }catch(ParseException e){
                    correctFormat = false;
                }
                }while(!correctFormat);

//Choosing sign

            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int day = cal.get(Calendar.DAY_OF_MONTH);
            int month = cal.get(Calendar.MONTH)+ 1;

// announcing sign
        //converting the day and month to a number to compare

                int zodiacNum = day * 100 + month;
                System.out.println(" zodiac number is " + zodiacNum);

//closing userInput                 
                userI 

Post Status

Asked in February 2016
Viewed 3,230 times
Voted 11
Answered 5 times

Search




Leave an answer