我有这两段代码:
int prevY = 0;
// this is the function InsertionSort applied to i
StdDraw.setPenColor(Color.blue);
for (int i = 1; i <= N; i++) {
int x = i;
int y = runInsertion(i);
int prevX = i - 1;
StdDraw.setPenRadius(lineRadius);
StdDraw.line(prevX, prevY, x, y);
StdDraw.setPenRadius(pointRadius);
StdDraw.point(x, y);
prevY = y;
}
prevY = 0;
// this is the function SelectionSort applied to i
StdDraw.setPenColor(Color.black);
for (int i = 1; i <= N; i++) {
int x = i;
int y = runSelection(i);
int prevX = i - 1;
StdDraw.setPenRadius(lineRadius);
StdDraw.line(prevX, prevY, x, y);
StdDraw.setPenRadius(pointRadius);
StdDraw.point(x, y);
prevY = y;
}
除了所使用的颜色和所使用的排序算法略有变化之外,它们都执行相同的操作。
有没有办法为颜色和排序算法创建一个数组,例如:
String[] algorithms = {"runInsertion", "runSelection"}
String[] colors = {"blue", "black"};
然后用for循环调用适当的索引,这样代码就被缩短了。
我知道这不会像我提议的那样起作用,但我只是想知道是否有某种方式或特定方法可以让我做到这一点。
最佳答案
只需将逻辑提取到具有所需参数的方法中即可:
void work(Color color, Function<Integer, Integer> algorithm) {
int prevY = 0;
StdDraw.setPenColor(color);
for (int i = 1; i <= N; i++) {
int x = i;
int y = algorithm.apply(i);
int prevX = i - 1;
StdDraw.setPenRadius(lineRadius);
StdDraw.line(prevX, prevY, x, y);
StdDraw.setPenRadius(pointRadius);
StdDraw.point(x, y);
prevY = y;
}
}
并调用它:
work(Color.blue, this::runInsertion);
work(Color.black, this::runSelection);
或者对于数组:
List<Function<Integer, Integer>> algorithms = Arrays.asList(this::runInsertion, this::runSelection);
List<Color> colors = Arrays.asList(Color.blue, Color.black);
for (int i = 0; i < algorithms.size(); i++) {
work(colors.get(i), algorithms.get(i));
}
关于java - 用 Java 中的循环替换代码中的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800700/