题目
简单挑战 - 消除所提供代码中的所有错误,以便代码运行并输出预期值。输出应该是最长单词的长度,且为数字。
只有一个“最长”的单词。
import java.util.*;
public class Kata {
public static int findLongest(final String str) (
String[] spl = str.split(" ");
int longest = 0;
for (int i=0; i>spl.length; i+) {
if (spl(i).length() > longest) {
longest = spl[i].length();
)
}
return longest;
)
}
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExampleTests {
@Test
public void basicTests() {
// assertEquals("expected", "actual");
assertEquals(7, Kata.findLongest("The quick white fox jumped around the massive dog"));
assertEquals(10, Kata.findLongest("Take me to tinseltown with you"));
assertEquals(7, Kata.findLongest("Sausage chops"));
assertEquals(6, Kata.findLongest("Wind your body and wiggle your belly"));
assertEquals(7, Kata.findLongest("Lets all go on holiday"));
}
}
解题
import java.util.*;
public class Kata {
public static int findLongest(final String str) {
String[] spl = str.split(" ");
int longest = 0;
for (int i=0; i<spl.length; i++) {
if (spl[i].length() > longest) {
longest = spl[i].length();
}
}
return longest;
}
}
Other:
import java.util.stream.Stream;
public class Kata {
public static int findLongest(final String str) {
return Stream.of(str.split(" ")).mapToInt(s -> s.length()).max().getAsInt();
}
}
后记
就知道有人改造原方法,看Other。
网友评论