获取在控制台上输入的值的数量

时间:2013-02-04 09:44:10

标签: java collections

在下面的代码中,我在第一个for循环中采用了三组值(i<3)。我能够使用不同的整数计算相同的数据,例如i<5i<6。请建议一种方法,我可以获取在控制台上输入的值的数量,然后将其用作<(number of values entered/2)

public static void main(String[] args) {

  Scanner s = new Scanner(System.in);
  System.out.println("please enter 3 birth - death pairs");
  List<Dinosaur> dinoList = new ArrayList<Dinosaur>();
  // int dinoStrength=s.nextInt();


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

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

1 个答案:

答案 0 :(得分:0)

Scanner s = new Scanner(System.in);
System.out.println("please enter 3 birth - death pairs");
List<Dinosaur> dinoList = new ArrayList<Dinosaur>();
// int dinoStrength=s.nextInt();


while(s.hasNextInt())
{

int num1 = s.nextInt();
int num2 = s.nextInt();
if(num2 ==num1)//Your condition(Here I assume date of birth should not be equal to death date.)
break;
Dinosaur d = new Dinosaur(num1, num2);
dinoList.add(d);

}

你可以尝试这样的事情。