我需要将 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/