I am having problems with my test. It looks like it's simple. All you have to do is delete a space, but I keep getting an error for some reason.
@Override
public String format(String template) {
if(template.equals("%t")){
return String.format("%02 seconds", getSeconds());
}
else if(template.equals("%h:%M:%S")) {
return String.format("%02d:%02d:%02d", getHours(), getMinutes(), getSeconds());
}
else if(template.equals("%d days, %h hours, %m minutes, and %s seconds")){
return String.format("%d days,%2d hours,%2d minutes, and %2d seconds", getDays(), getHours(),
getMinutes(), getSeconds());
}
else return null;
}
@Test
public void testFormatExample1() {
assertEquals("3 days, 4 hours, 0 minutes, and 9 seconds",
fromDHMS(3, 4, 0, 9)
.format("%d days, %h hours, %m minutes, and %s seconds"));
}
This is what I should get
3 days, 4 hours, 0 minutes, and 9 seconds
yet this is what I keep getting
Expected :3 days, 4 hours, 0 minutes, and 9 seconds
Actual :3 days, 4 hours, 0 minutes, and 9 seconds
I've tried everything to get rid of that extra space in and 9 seconds
If I go to the last case of my if statement, and I delete the space between and
and %2d seconds
, It still doesn't work. I did it for the spaces before it and it worked.
Does anyone know the problem?
The problem is just %2d
- you've explicitly asked for the number of seconds to be converted into a minimum of two characters. Just make it %d
and it should be fine. See the Formatter
documentation for details.
Note that at the moment, if you have 10 or more hours and 10 or more minutes, you probably won't get the output you expect - you'll have no space after the comma. I suspect you want a format string of:
"%d days, %d hours, %d minutes, and %d seconds"
As an aside, however, I don't think that only accepting some very specific input templates is a very good idea - if that's all you need to support, I'd use an enum to represent them instead.
See more on this question at Stackoverflow