学习有关超技能的Java。陷入战略话题。社区没有响应,我不明白为什么我没有得到正确的结果。请帮忙。 我假设我没有得到这部分的实际含义:“如果数组为空,则查找器应在找到最小值时返回Integer.MAX_VALUE,在找到最大值时应返回Integer.MIN_VALUE。”
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
class Finder {
private FindingStrategy strategy;
public Finder(FindingStrategy strategy) {
this.strategy = strategy;
}
/**
* It performs the search algorithm according to the given strategy
*/
public int find(int[] numbers) {
return this.strategy.getResult(numbers);
}
}
interface FindingStrategy {
/**
* Returns search result
*/
int getResult(int[] numbers);
}
class MaxFindingStrategy implements FindingStrategy {
@Override
public int getResult(int[] numbers) {
if (numbers.length > 0 ){
Arrays.sort(numbers);
return numbers[0];
} else {
return Integer.MIN_VALUE;
}
}
}
class MinFindingStrategy implements FindingStrategy {
@Override
public int getResult(int[] numbers) {
if (numbers.length > 1 ){
Arrays.sort(numbers);
return numbers[numbers.length-1];
} else {
return 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));
}
}
答案 0 :(得分:2)
这个想法是,当没有可用输入时,您需要返回Integer.MAX_VALUE
或Integer.MIN_VALUE
。如果请求是从输入中查找最小值,但输入为空,则返回Integer.MAX_VALUE
;或者,如果输入为空并且请求最大值,则返回Integer.MIN_VALUE
。
您的具体问题是因为此;
if (numbers.length > 1 ){
您需要检查长度是否大于0,而不是1。
答案 1 :(得分:0)
我将使用流来完成这项工作:
Arrays.stream(numbers).min().orElse(Integer.MIN_VALUE);
Arrays.stream(numbers).max().orElse(Integer.MAX_VALUE);
由于使用此流,您不必检查numbers.length
,也解决了检查numbers.length > 1
而不是numbers.length > 0
的问题。