当前位置: 代码迷 >> 综合 >> Exercism————Proverb
  详细解决方案

Exercism————Proverb

热度:41   发布时间:2023-12-13 18:12:29.0

题目:

在这里插入图片描述

解法一:

package exercism;public class Proverb {
    private String[] list;public Proverb(String[] list) {
    this.list = list;}String generateProverb(String[] list) {
    StringBuilder output = new StringBuilder();for (int i = 0; i < list.length - 1; i++) {
    String content = String.format("For want of a %s the %s was lost \n",list[i],list[i+1]);output.append(content);}output.append("And all for the want of " + list[0]);return  output.toString();}}

解法二:

import java.util.stream.Collectors;
import java.util.stream.IntStream;class Proverb {
    private final String[] words;Proverb(String[] words) {
    this.words = words;}String recite() {
    return IntStream.range(0, words.length).mapToObj(this::format).collect(Collectors.joining("\n"));}private String format(int s) {
    return s != words.length - 1 ?"For want of a " + words[s] + " the " + words[s + 1] + " was lost.": "And all for the want of a " + words[0] + ".";}
}

总结: