类Finder
代表常规发现算法本身。它具有find(int[] numbers)
方法,该方法根据指定的策略返回查找结果。
接口FindingStrategy
提供了getResult()
方法来编写新的具体发现策略。
请不要更改界面FindingStrategy
,也不要重命名现有方法。
如果数组为空,则Finder
在返回最小值时应返回Integer.MAX_VALUE
,在找到最大值时应返回Integer.MIN_VALUE
。
我尝试使用流,但是它不起作用。当我尝试使用for循环检查numbers.length > 0
时,它也不正确。
class Finder {
private FindingStrategy strategy;
public Finder(FindingStrategy strategy) {
// write your code here
this.strategy = strategy;
}
/**
* It performs the search algorithm according to the given strategy
*/
public int find(int[] numbers) {
// write your code here
return this.strategy.getResult(numbers);
}
}
interface FindingStrategy {
/**
* Returns search result
*/
int getResult(int[] numbers);
}
class MaxFindingStrategy implements FindingStrategy {
@Override
public int getResult(int[] numbers) {
// write your code here
return Arrays.stream(numbers).min().orElse(Integer.MIN_VALUE);
}
}
class MinFindingStrategy implements FindingStrategy {
public int getResult(int[] numbers) {
return Arrays.stream(numbers).max().orElse(Integer.MAX_VALUE);
}
}
/* Do not change code below */
public class Main {
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
final String[] elements = scanner.nextLine().split("\\s+");
int[] numbers = null;
if (elements[0].equals("EMPTY")) {
numbers = new int[0];
} else {
numbers = new int[elements.length];
for (int i = 0; i < elements.length; i++) {
numbers[i] = Integer.parseInt(elements[i]);
}
}
final String type = scanner.nextLine();
Finder finder = null;
switch (type) {
case "MIN":
finder = new Finder(new MinFindingStrategy());
break;
case "MAX":
finder = new Finder(new MaxFindingStrategy());
break;
default:
break;
}
if (finder == null) {
throw new RuntimeException(
"Unknown strategy type passed. Please, write to the author of the problem.");
}
System.out.println(finder.find(numbers));
}
}```