Discuss / Java / 练习

练习

Topic source

狠美味2013

#1 Created at ... [Delete] [Delete and Lock User]

package com.itranswarp.world;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Time {

/**

* 从"21:05:19"中提取时,分,秒,否则抛出IllegalArgumentException

*/

public static int[] parseTime(String s) {

String regex = "([0-1][0-9]|2[0-4]):([0-6][0-9]):([0-6][0-9])";

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(s);

if (matcher.matches()) {

int[] i = new int[3];

i[0] = Integer.parseInt(matcher.group(1));

i[1] = Integer.parseInt(matcher.group(2));

i[2] = Integer.parseInt(matcher.group(3));

return i;

} else {

throw new IllegalArgumentException();

}

}

}

package com.itranswarp.world;

import static org.junit.Assert.*;

import org.junit.Test;

public class TimeTest {

@Test

public void testParseTime() {

assertArrayEquals(new int[] { 0, 0, 0 }, Time.parseTime("00:00:00"));

assertArrayEquals(new int[] { 1, 2, 3 }, Time.parseTime("01:02:03"));

assertArrayEquals(new int[] { 10, 20, 30 }, Time.parseTime("10:20:30"));

assertArrayEquals(new int[] { 12, 34, 56 }, Time.parseTime("12:34:56"));

assertArrayEquals(new int[] { 23, 59, 59 }, Time.parseTime("23:59:59"));

}

/*

* @Test public void testParseTimeFailed() {

* isEquals(IllegalArgumentException.class, () -> { Time.parseTime(null);

* }); assertThrows(IllegalArgumentException.class, () -> {

* Time.parseTime(""); }); assertThrows(IllegalArgumentException.class, ()

* -> { Time.parseTime("24:00:00"); });

* assertThrows(IllegalArgumentException.class, () -> {

* Time.parseTime("23:60:59"); });

* assertThrows(IllegalArgumentException.class, () -> {

* Time.parseTime("10:1:2"); }); }

*/

}


  • 1

Reply