自学内容网 自学内容网

Java习题集合的灵活应用

一题目要求:

二具体代码:

Ⅰ实体类:

package three;

public class People {
    private int number;
    private int position;

    public People() {
    }

    public People(int number, int position) {
        this.number = number;
        this.position = position;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    @Override
    public String toString() {
        return "People{" +
                "number=" + number +
                ", position=" + position +
                '}';
    }
}

Ⅱ主函数

package three;

import java.util.*;

public class test {
    public static List<People> arrayList=new ArrayList<>();
    public static void main(String[] args) {
        Random sc=new Random();
        for (int i = 1; i <= 100 ; i++) {
            while (true) {
                int index= sc.nextInt(200)+1;
                if(judge(index)){
                    arrayList.add(new People(index,i));break;
                }
            }
        }
        //System.out.println(arrayList);

        while (arrayList.size()>1){
            List<People> temp=new ArrayList<>();
            for (int i = 1; i <arrayList.size() ; i+=2) {
                temp.add(arrayList.get(i));
            }
            arrayList=temp;
        }
        System.out.println("幸存者为"+arrayList.get(0).getPosition()+"位置上的编号为" +
                arrayList.get(0).getNumber());
    }

    private static boolean judge(int index) {
        for (People people : arrayList) {
            if (people.getNumber()==index) return false;
        }
        return true;
    }
}


原文地址:https://blog.csdn.net/mrjieke6/article/details/140541708

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!