-1

在下面的代码中,我得到了基于我自己定义的数组列表的输出。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DinoMania {

public static void main(String[] args) {
    List<Dinosaur> dinoList = new ArrayList<Dinosaur>();
    Dinosaur d1 = new Dinosaur(1970, 1985);
    Dinosaur d2 = new Dinosaur(1980, 1981);
    Dinosaur d3 = new Dinosaur(1990, 2015);
    Dinosaur d4 = new Dinosaur(2000, 2007);
    Dinosaur d5 = new Dinosaur(2010, 2012);
    Dinosaur d6 = new Dinosaur(2020, 2030);
    Dinosaur d7 = new Dinosaur(2030, 2035);

    dinoList.add(d7);
    dinoList.add(d6);
    dinoList.add(d5);
    dinoList.add(d4);
    dinoList.add(d3);
    dinoList.add(d2);
    dinoList.add(d1);

    //System.out.println(dinoList);

    Collections.sort(dinoList);

    //System.out.println(dinoList);
    int maxCount = 0;
    List<String> ls=new ArrayList<String>();

    for (Dinosaur dino : dinoList) {

        // System.out.println("start date" + dino.getStartDate());
        // System.out.println("end date"+ dino.getEndDate());
        int count = 0;
        for (Dinosaur dino2 : dinoList) {

            if (dino2.getStartDate() <= dino.getEndDate()
                    && dino2.getEndDate() >= dino.getStartDate())
                count++;

        }
        //System.out.println(count);

        if (maxCount < count) {
            maxCount = count;
            ls.clear();
            ls.add(dino.getStartDate()+"-"+dino.getEndDate());
        }

        else if(maxCount==count)

        {
            ls.add(dino.getStartDate()+"-"+dino.getEndDate());
        }
    }
    //System.out.println(maxCount);

//System.out.println(ls);

System.out.println("Max no of Dinos alive at the same time :"+maxCount);
}

}

我想知道当用户从控制台输入时如何动态定义数组列表

4

1 回答 1

0

你可以使用这样的东西:

Scanner s = new Scanner(System.in);
    System.out.println("please enter 5 records");
    List<Dinosaur> dinoList = new ArrayList<Dinosaur>();

    for (int i = 0; i < 5; i++) {
        int num1 = s.nextInt();
        int num2 = s.nextInt();
        Dinosaur d = new Dinosaur(num1, num2);
        dinoList.add(d);

    }
于 2013-02-04T07:08:27.500 回答