0

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 complication implementing minor suggestion to make the code function the right way,

what i got so far is :

boolean correctFormat = false;      
                do{

                System.out.println(userName + " please enter you DoB (DD/MM/YYY)");
                String dateOB = userInput.next();

                try{ 
                Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
                                    System.out.println(dateOB);
                System.out.println("So your date of birth is " + dateOB);
                correctFormat = true;

                }catch(ParseException e){

                correctFormat = false;
                }
                }while(!correctFormat);

So the problem i am facing is that " dateOB is now since it is inside a while loop, is not recognized out side the loop, which is checking if the date format is right , so when i try and conver the date to a number : int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(dateOB));

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

it is not accepted ? how do i tackle this issue ? enter image description here

Hey so far i've been having some trouble with part of the code:

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

as in eclips it wont let me get the day and the month from "dateOB" with this code. enter image description here

could someone try and help me understand what is the problem !?

3
  • Any error/exception for you to help? What was the input that you passed? Commented Feb 8, 2016 at 8:12
  • dateOB is a String value. You can not just put it in the int type value. And MM is different from mm. MM stands for month and mm stands for minute. Commented Feb 8, 2016 at 8:15
  • Simple way to change the string to int is int date = Integer.parseInt(dateOB.substring(0,2)), int month = Integer.parseInt(dateOB.substring(2,4)) and so far. And then you can compare it with another int date value. Commented Feb 8, 2016 at 8:24

6 Answers 6

1

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());
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Stefano thank you very much for this insight, you just made me find out about new ways to one thing in java, and i'll made sure to apply your way to learn it, but right now i am trying to achieve converting a simple input data from the user as DoB into an integer in order for me to use it in a switch case method to compare it to zodiac ( different cases) also i am trying to figuer out how to make a loop in order to make sure the input of the date is as formated dd/MM/yyyy
@Ahmed a good way to be sure if input is in the correct format is to use df.format(date), catch the ParseException if is not and ask it again !.
1

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();
}

2 Comments

Dato, thank you for the full code, which helped me to go over the steps to understand how to use the SimpleDateFormat, but applying the exact code you provided without the "if" statement, i wanted to under stand the product of the code, so after correcting my mistake on the MM instead of mm, and adding the Calendar c = Calendar.getInstance(); to int day = .... i went and added the System.out.println(day); to see what sofar have been converted, and it gave me a number 310 ? for a DoB ( 05/11/1984) i entered as an input !?
Yes 5 November of 1984 is 310 day of the year
1

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");
    } else if (mmdd >= 823 && mmdd <= 922) {
        System.out.println("VIRGO");
    } else if (mmdd >= 923 && mmdd <= 1022) {
        System.out.println("LIBRA");
    } else if (mmdd >= 1023 && mmdd <= 1121) {
        System.out.println("SCORPIO");
    } else if (mmdd >= 1122 && mmdd <= 1221) {
        System.out.println("SAGITTARIUS");
    } else if ((mmdd >= 1222 && mmdd <= 1231) || (mmdd >= 11 && mmdd <= 119)) {
        System.out.println("CAPRICORN");
    } else if (mmdd >= 120 && mmdd <= 218) {
        System.out.println("AQUARIUS");
    } else if (mmdd >= 219 && mmdd <= 320) {
        System.out.println("PISCES");
    }
}

Test using netbeans 8.0.1

Nb: I used Netbeans 8.0.1

4 Comments

Hey, cdaiga ... i've tried your way which is close to Datos and Lord suggestion but shorter and i understand it, but after i wrote this code you provided ( int userVal ............... ) i went ahead and printed the userVal tosee the number the code converted my date of birth to, which should've been 0511 or 511 but i got an error : Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date at java.text.DateFormat.format(DateFormat.java:301) at java.text.Format.format(Format.java:157) at signs.main(signs.java:34)
I just modified the code, I have tested that already and it works. Cool, you understood my algorithm.
as you could see i added couple of screen shot, showing the problem i am having now, i declared the dateOB outside the loop then used in the loop, to parseint .... but then again when i tried to get the day and the month from the date after the conversion with the code provided as you suggested, it seems that there is some kind of conflict !?
I have seen the changes, but I think that's not the implementation. If you check very well when you extract the month and the day ("MMdd") of the date we get different values for different dates. This string value can be converted into an integer which could be use to locate the zodiac sign using if-else statements.
1

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                 
                userInput.close();
}       
}

Thank you again guys, i hope this could be helpful for someone with basic knowledge as mine, and help them understand some issues.

Comments

0

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 SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
    (...)
} while (...);
int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(date);
(...)
cal.setTime(date);
(...)

It is important for you to know that date is the real date whereas dateOB is only what the user entered - this String cannot be used as real date!

7 Comments

Lord, thank you for the reply, as you could see i faced a problem applying this code, or maybe i didnt understand what it does ... check my comment for Dato's suggestion, i did the same with your suggestion, then at the end, i asked the program to print out ( day + " " + month ) to see the prodcut of this code you suggested and, the output was ( 310 10 ) so i am not sure how this come up to be the conversion of the DoB i provided which is 05/11/1984 .... i expected it to give me a number such as 511, or 0511 ... in order to compare it to other zodiac signs such as aquarius 120 -218
I made one mistake, because Calendar.MONTH reaches from 0 to 11, other than that it works fine for me ("5 10" and after changing it to int month = cal.get(Calendar.MONTH) + 1 I received "5 11"). It probably does not give you the numbers you want, but you can still compare it to zodiac signs by checking whether month and day fit into a sign.
Perfect, adding +1 to the code solved the problem, and thank you for helping understand what was the problem ( Calendar.Month reachs only 11) so after doing that i do get a correct number of 511 and i converted that to zodiacNumber to ease comparison between zodiac sign, the thing i am facing now is implementing the loop method you suggested
as you could see in the picture i add to the post, in eclips, after adding the code: do { --------> while; and then trying to implement the conversion of the day and month to a number, the program is not able to use " dateOB ", not sure how to go on from here to finish the code ?
You need to declare dateOB outside the loop (otherwise the variable will only be available during the loop). That means you initialize String dateOB = ""; before the loop and then it is available during the whole method. :) Edit: java-made-easy.com/variable-scope.html this link explains how the scope of variables works.
|
0

java.time

You are using terribly-flawed date-time classes that are now legacy. Use only the modern java.time classes. Never use Calendar, Date, etc.

For a date-only value, without time-of-day, and without time zone, use LocalDate class.

compare it to zodiac signs dates in a switch format

No can do with switch. But you can use a series of if tests.

Notice in this code how we declare our birthDate and astrology variables before the repeat loop. Then we assign object references to those variables within the loop. The loop can test for null to detect whether the user has accomplished their task or not.

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "dd/MM/uuuu" ) ;
LocalDate birthDate = null ;
String astrology = null ;

repeat
{
    … // Gather input from user.
    try 
    {
        birthDate = LocalDate.parse ( input , formatter ) ;

        final int dayOfYear = date.getDayOfYear ( );
        if ( dayOfYear < 100 ) { astrology = "Aquarius"; }
        else if ( dayOfYear < 200 ) { astrology = "Taurus"; }
        else { astrology = "Whatever"; }
    }
    catch ( DateTimeParseException e ) 
    {
        … // Explain error to user. Prompt for input again.
    }
}
while ( Objects.isNull ( birthDate ) ) ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.