java - 需要读入 ArrayList 并将正数和负数分开

标签 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);
   }
}

最佳答案

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

关于java - 需要读入 ArrayList 并将正数和负数分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7293668/

相关文章:

java - 工厂模式示例 - 需要以下代码的解决方案

java - 指定 ArrayList 的类型

java - maven-application.xml 文件有什么用?

c++ - 将数组传递给 Cuda

c++ - C++中的std::vector与[]比较慢-为什么?

c++ - 'auto' 关键字是否知道何时使用 const 迭代器?

java - 从 Eclipse 项目读取文件

PHP:为具有嵌套关联数组的对象公开 'get' 和 'set'

c# - 每行打印出数组中的 3 个元素

list - 如何将两个变量列表相乘