Java 接口作为参数,返回结果
我正在做以下编程练习:。声明如下: 您将获得一个由n行组成的字符串,每个子字符串为n个字符 龙:例如: s=“abcd\nefgh\nijkl\nmnop” 我们将研究这个弦平方的一些变换Java 接口作为参数,返回结果,java,function,methods,lambda,java-8,Java,Function,Methods,Lambda,Java 8,我正在做以下编程练习:。声明如下: 您将获得一个由n行组成的字符串,每个子字符串为n个字符 龙:例如: s=“abcd\nefgh\nijkl\nmnop” 我们将研究这个弦平方的一些变换 Vertical mirror: vert_mirror (or vertMirror or vert-mirror) vert_mirror(s) => "dcba\nhgfe\nlkji\nponm" Horizontal mirror: hor_mirror (or horMirror or
Vertical mirror: vert_mirror (or vertMirror or vert-mirror)
vert_mirror(s) => "dcba\nhgfe\nlkji\nponm"
Horizontal mirror: hor_mirror (or horMirror or hor-mirror)
hor_mirror(s) => "mnop\nijkl\nefgh\nabcd"
或打印:
垂直镜像|水平镜像abcd-->dcba | abcd-->
mnop efgh hgfe | efgh ijkl IKKL lkji | ijklefgh mnop ponm | mnop abcd 任务: 及
high-order function oper(fct, s) where
fct is the function of one variable f to apply to the string s (fct will be one of vertMirror, horMirror)
示例:
s=“abcd\nefgh\nijkl\nmnop”操作(垂直镜像,s)=>
“dcba\nhgfe\nlkji\nponm”操作(后视镜,s)=>
“mnop\nijkl\nefgh\nabcd”
我需要一些帮助,因为这是我第一次需要将函数作为方法的参数传递。初始测试用例(取自练习):
我尝试了以下实现:
import java.util.function.*;
类Opstrings{
公共静态字符串vertMirror(字符串字符串){
String[]words=String.split(\\s+);
StringBuilder sb=新的StringBuilder();
for(字符串字:字){
sb.append(新的StringBuilder(word).reverse()+“\n”);
}
返回字符串.strip().toString();
}
公共静态字符串镜像(字符串){
返回新的StringBuilder(string).reverse().toString();
}
public static String oper/*Consumer
是从某物到某物(void)的函数。Callable
是从某物到某物的函数。您需要从某物到另一物的函数
或者,因为返回类型和参数类型在您的情况下是相同的,.消费者是从某个对象到某个对象的函数(void)。可调用的
是从某个对象到某个对象的函数。您想要从某个对象到另一个对象的函数
或者,由于返回类型和参数类型在您的案例中是相同的
high-order function oper(fct, s) where
fct is the function of one variable f to apply to the string s (fct will be one of vertMirror, horMirror)
import static org.junit.Assert.*;
import org.junit.Test;
public class OpstringsTest {
private static void testing(String actual, String expected) {
assertEquals(expected, actual);
}
@Test
public void test() {
System.out.println("Fixed Tests vertMirror");
String s = "hSgdHQ\nHnDMao\nClNNxX\niRvxxH\nbqTVvA\nwvSyRu";
String r = "QHdgSh\noaMDnH\nXxNNlC\nHxxvRi\nAvVTqb\nuRySvw";
testing(Opstrings.oper(Opstrings::vertMirror, s), r);
s = "IzOTWE\nkkbeCM\nWuzZxM\nvDddJw\njiJyHF\nPVHfSx";
r = "EWTOzI\nMCebkk\nMxZzuW\nwJddDv\nFHyJij\nxSfHVP";
testing(Opstrings.oper(Opstrings::vertMirror, s), r);
System.out.println("Fixed Tests horMirror");
s = "lVHt\nJVhv\nCSbg\nyeCt";
r = "yeCt\nCSbg\nJVhv\nlVHt";
testing(Opstrings.oper(Opstrings::horMirror, s), r);
s = "njMK\ndbrZ\nLPKo\ncEYz";
r = "cEYz\nLPKo\ndbrZ\nnjMK";
testing(Opstrings.oper(Opstrings::horMirror, s), r);
}
}