Search code examples
javastringsplitparseint

How to split the string inputted by user


This is for our assignment in Java Programming. I want to know how to split an inputted string by the user.
The program will ask the user to input his birth date in MM/dd format. After that I want the application to split the date (delimiter is the slash). Add the number. And output the zodiac sign base on the sum of the number.

Expected result :

Please enter your date of birth (MM/dd): 01/06
This is the mmdd value: 106
Result: Capricorn

But I am not getting this result with the following code:

public static void main(String[] args) {

    Scanner scan = new Scanner (System.in);
    int mmdd;
    int a;
    int b;

   System.out.print("Please enter your date of birth(MM/dd): ");
   String stringdate = scan.next();

   a = Integer.parseInt(stringdate.split("/") [0]);
   b = Integer.parseInt(stringdate.split("/") [1]);
   mmdd = a + b;

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

   System.out.print("Result: ");
     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");
     }
}

Solution

  • a = Integer.parseInt(stringdate.split("/") [0]); gives you 1
    b = Integer.parseInt(stringdate.split("/") [1]); gives you 6

    So in fact you are summing 1 + 6 for that you get 7 and not 106.

    Instead you can use :

    String stringdate = scan.next();
    stringdate = stringdate.replaceAll("[^\\d]+", "");//remove all non digits
    
    mmdd = Integer.parseInt(stringdate);//then parse the result
    

    If you enter 01/06 then mmdd return 106 and not 7