2

I want make to make hours and minutes arrays which for 19:49 should contain

hours[0] = 1
hours[1] = 9
minutes[0] = 4
minutes[1] = 9

Problem is that when I execute code:

Calendar rightNow = Calendar.getInstance();
String hour[] = String.valueOf(rightNow.get(Calendar.HOUR_OF_DAY)).split("");
String minute[] = String.valueOf(rightNow.get(Calendar.MINUTE)).split("");

and when I print this

System.out.println(hour[0] + ""+hour[1] + ":" + minute[0] +""+minute[1]);

I have this output 1:4, but it should be 19:49

Update: I am using 1.7 JDK and form what I see hour[2] contains 9 and minute[2] 9.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Larry
  • 101
  • 9

2 Answers2

2

Problem in pre-Java-8 is that when we split(delimiter) string like

delimiter[Data]delimiter[Data]delimiter[Data]

we will get as result array

"", "[Data]", "[Data]", "[Data]"

In your case delimiter is empty string "", and empty string exists not only inbetween characters, but also at start and end of string.

To solve this problem you could use split("(?!^)") which will split on each place as long it doesn't have start of string (^) after it (which excludes empty string at start of your text).

In Java 8 this behaviour changed: Why in Java 8 split sometimes removes empty strings at start of result array?

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

Well I guess what you are looking for is something like this

    int[] hour = new int[2];
    int[] minute = new int[2];

    Calendar rightNow = Calendar.getInstance();

    int tempHour = rightNow.get(Calendar.HOUR_OF_DAY);
    int tempMin  = rightNow.get(Calendar.MINUTE);

    hour[0]   = (int)Math.floor(tempHour/10);
    hour[1]   = tempHour%10;

    minute[0] = (int)Math.floor(tempMin/10);
    minute[1] = tempMin%10;

    System.out.println(hour[0] + "" + hour[1] + ":" + minute[0] + "" + minute[1]);
Kyle Luke
  • 348
  • 5
  • 16
  • no i want to have array int hour[] and array int minute[] and when we have 10:31 in arrays i should have hour[0] = 1 hour[1] = 0 minute[0] = 3 minute[1] = 1 – Larry Jan 01 '16 at 11:47
  • edited. Check this out. If any explanations needed feel free to ask) – Kyle Luke Jan 01 '16 at 14:56