Exercism————Proverb

题目:

Exercism————Proverb_第1张图片

解法一:

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] + ".";
    }
}

总结:

你可能感兴趣的:(Exercism)