开发者

Need to read into an ArrayList and separate Positive and Negative numbers

开发者 https://www.devze.com 2023-04-02 00:10 出处:网络
I need to read in 10 integers into an ArrayList and then have to program sort them into two groups: \"Positive Integers\" and \"Negative Integers\".

I need to read in 10 integers into an ArrayList and then have to program sort them into two groups: "Positive Integers" and "Negative Integers".

I have two ArrayLists and an if statement to determine where each integer should go, however I do not know what variable to use in order to make this work. Here is what I have so far:

import java.util.*;
public class Sort {
  public static void main (String [] args) {
      ArrayList<Integer> pos = new ArrayList<Integer>();
      ArrayList<Integer> neg = new ArrayList<Integer>();
      Scann开发者_如何学运维er 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);
   }
}


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++;
}


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


You can use a navigable set.. Add the numbers to it and then just query for the head or tail by passing 0 as the argument. Let me know if you want me to elaborate.

0

精彩评论

暂无评论...
验证码 换一张
取 消