需要读入 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);
}
}
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 ArrayList
s 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用可导航集。向其中添加数字,然后通过传递 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.