Java-Huawei real test questions-book a hotel

need:

   It’s summer vacation. Xiao Wang decided to visit a tourist attraction. He searched for hotels of various price ranges on the Internet (array A of length n). His psychological price is x yuan. Please help him filter out k hotels that are closest to x. Yuan hotels (n>=k>0), and print the hotel prices from low to high.
1) The hotel price array A and Xiao Wang’s psychological price x are both integer data; (0 < n, k, x < 10000)
2) Give priority to the hotel with the price closest to the psychological price; if the difference between the two hotels and the psychological price is the same, choose the hotel with the lower price. (For example, 100 yuan and 300 yuan are equally close to the psychological price of 200 yuan, so choose 100 yuan at this time);
3) Hotel prices may be the same and repeated.
Input description: 
  First line: n, k, x 
  Second line: A[0] A[1] A[2]…A[n-1] 

Output description: 
  Print the filtered hotel prices from low to high

coding:

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

Effect:

Guess you like

Origin blog.csdn.net/hlx20080808/article/details/132823282