I'm working on a method that takes a string time, which contains 3 to 4 numbers representing military time, such as "130" or "1245". The purpose of this method is to assign the contents of the string time to an integer array with two parts: [0] is the hour (such as "1" or "12" from my example above), and [1] represents the minutes ("30" or "45" from my example).
The if(str.length() ==3) is meant to catch strings such as "130", where the hour is less than 10 and the string lacks a leading zero.
When I compile, the errors I get read:
error: incompatible types
temp = a[1] + a[2];
^
required: String
found: int
.
error: incompatible types
temp = a[0] + a[1];
^
required: String
found: int
.
error: incompatible types
temp = a[2] + a[3];
^
required: String
found: int
.
I've been reading up on the char data type, and from what I understand it has a numerical value similar to an integer. I've attempted to typecast with:
temp = (String) a[1] + a[2];
But that gives the following error:
error: inconvertible types
temp = (String) a[1] + a[2];
^
required: String
found: char
At this point I'm not sure what to do. Below is my code:
private int[] convertStringToHoursMins(String time) {
String str = time;
String temp;
char[] a = str.toCharArray();
int[] hoursMins = new int[2];
try {
if (str.length() == 3) {
hoursMins[0] = a[0];
temp = a[1] + a[2];
hoursMins[1] = Integer.parseInt(temp);
}
else {
temp = a[0] + a[1];
hoursMins[0] = Integer.parseInt(temp);
temp = a[2] + a[3];
hoursMins[1] = Integer.parseInt(temp);
}
}
catch(NumberFormatException e) {
System.out.println("Invalid time.");
}
return hoursMins;
}
Thanks in advance for any help you can offer.