策略最小值最大值

问题描述

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));
   }
}```










解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...