需要读入ArrayList并分隔正数和负数

时间:2011-09-03 14:18:24

标签: java arrays loops arraylist

我需要将10个整数读入ArrayList,然后必须将它们编程为两组:“正整数”和“负整数”。

我有两个ArrayList和一个if语句来确定每个整数应该去哪里,但是我不知道要使用哪个变量来使这个工作。以下是我到目前为止的情况:

import java.util.*;
public class Sort {
  public static void main (String [] args) {
      ArrayList<Integer> pos = new ArrayList<Integer>();
      ArrayList<Integer> neg = new ArrayList<Integer>();
      Scanner sc = new Scanner(System.in);

      int i=0 ;

      while(i <= 10) {
          System.out.println("enter an integer");
          if(??? < 0) {  //here is where my question is
              neg.add(sc.nextInt());
          } else {
              pos.add(sc.nextInt());
          }

          i++;  
      }
      System.out.println("positive numbers" + pos);
      System.out.println("negative numbers" + neg);
   }
}

3 个答案:

答案 0 :(得分:4)

while(i<=10){
    System.out.println("enter an integer");
    int next_int = sc.nextInt();
    if(next_int < 0) {  //here is where my question is
        neg.add(next_int);
    } else {
        pos.add(next_int);
    }

    i++;
}

答案 1 :(得分:3)

int number = sc.nextInt()
if(number<0){
    neg.add(sc.nextInt());
}
else{
    pos.add(sc.nextInt());
}

答案 2 :(得分:0)

您可以使用可导航的集合。将数字添加到它,然后通过传递0作为参数来查询头部或尾部。如果您要我详细说明,请告诉我。