Java-华为真题-预定酒店

需求:

复制代码
   放暑假了,小王决定到某旅游景点游玩,他在网上搜索到了各种价位的酒店(长度为n的数组A),他的心理价位是x元,请帮他筛选出k个最接近x元的酒店(n>=k>0),并由低到高打印酒店的价格。
复制代码
 1)酒店价格数组A和小王的心理价位x均为整型数据;(0 < n,k,x < 10000)
复制代码
 2)优先选择价格最接近心理价位的酒店;若两家酒店和心理价位差价相同,则选择价格较低的酒店。(比如100元和300元距离心理价位200元同样接近,此时选择100元);
复制代码
3)酒店价格可能相同重复。
复制代码
输入描述:
  第一行:n, k, x
  第二行:A[0] A[1] A[2]…A[n-1]

输出描述:
  由低到高打印筛选出的酒店价格

编码:

java 复制代码
public class ReservationHotel {
    public static void main(String[] args) {
        //使用useDelimiter()方法,输入一起输入
        Scanner sc = new Scanner(System.in).useDelimiter("\\D");
        System.out.print("请输入:");
        int count=sc.nextInt();
        int number=sc.nextInt();
        int money=sc.nextInt();
        //调用方法
        show(count,number,money,sc);
    }

    /**
     *
     * @param count 数组长度
     * @param number 筛选个数
     * @param money 目标价位
     */
    public static void show(int count,int number,int money, Scanner sc ){
       //(1)集合存放各个酒店价格数据
        List<Integer> hotelPriceList = new ArrayList<>();
        System.out.print("请输入"+count+"个酒店价格:");
        for (int i = 0; i <count ; i++) {
            hotelPriceList.add(sc.nextInt());
        }
       // (2)根据酒店价格从低到高排序
        Collections.sort(hotelPriceList,(o1, o2) -> {
            //心理价位差价
            int dif1=Math.abs(o1-money);
            int dif2=Math.abs(o2-money);
//            比较不等
            if (dif1!=dif2){
                return Integer.compare(dif1,dif2);
            }else{
                return  Integer.compare(o1,o2);
            }
        });

        System.out.println("进行比较后的酒店价格:"+hotelPriceList.toString());

        //(3)将集合存放各个筛选出number个最接近money元的酒店
        List<Integer> findPriceList = new ArrayList<>();
        for (int i = 0; i <number ; i++) {
            findPriceList.add(hotelPriceList.get(i)); //获取酒店筛选出数据
        }

        //(4)再按酒店价格从低到高排序
        Collections.sort(findPriceList);

        System.out.println("筛选出最接目标价位"+money+"元的酒店:"+findPriceList.toString());
    }
}

效果:

相关推荐
步行cgn21 分钟前
Spring MVC 视图机制的核心接口与类
java·开发语言·后端·spring·mvc
y1su37 分钟前
Leetcode 字符串模板
java·数据结构·算法·leetcode·职场和发展·动态规划
传奇开心果编程1 小时前
【Rust入门练中学】第5课:引用与借用
开发语言·rust·引用·编程语言理论·通用编程语言·借用
qetfw1 小时前
Bash 变量:export、位置参数与默认值展开验证
linux·开发语言·chrome·bash
电子云与长程纠缠1 小时前
UE5魂系游戏开发教程05
开发语言·学习·游戏·ui·ue5
cspttty2 小时前
2027风险管理岗准备路线:数学与应用数学如何补齐金融、SQL与Python
开发语言·python·金融
我命由我123452 小时前
Python 开发 - Python 的 pathlib
java·开发语言·后端·python·学习·java-ee·学习方法
苜蓿muxu2 小时前
Java 字符串拼接:+、StringBuilder、StringBuffer的区别
java
严谨的麻辣烫2 小时前
Python HTTP 连接池怎么用?从连接复用到请求异常排查
开发语言·python·http·requests·网络排查
摇滚侠2 小时前
《Java并发编程之美》第 4 章 Java 并发包中原子操作类原理剖析 阅读笔记 7
java·笔记·python