我需要將10個整數讀入ArrayList
,然後必須將它們編程爲兩組:「正整數」和「負整數」。需要讀入ArrayList並分開正數和負數
我有兩個ArrayList
s和一個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);
}
}
這是一個集合,不會支持雙重條目。如果有人兩次輸入「1」,那麼「1」只會在輸出中出現一次,而不是兩次。這可能不是用戶想要的:) – extraneon
嗯,我同意,雖然根據用例的另一種變化,可以使用導航地圖。其優點是數據結構封裝了存儲數據的用戶邏輯,並減少了用戶代碼中的分支。 – Scorpion