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

发布于 2024-12-02 16:31:27 字数 827 浏览 0 评论 0原文

我需要将 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);
   }
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月光色 2024-12-09 16:31:27
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++;
}
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++;
}
橘香 2024-12-09 16:31:27
int number = sc.nextInt()
if(number<0){
    neg.add(sc.nextInt());
}
else{
    pos.add(sc.nextInt());
}
int number = sc.nextInt()
if(number<0){
    neg.add(sc.nextInt());
}
else{
    pos.add(sc.nextInt());
}
不疑不惑不回忆 2024-12-09 16:31:27

您可以使用可导航集。向其中添加数字,然后通过传递 0 作为参数来查询头部或尾部。如果您想让我详细说明,请告诉我。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文