2011-09-03 18 views
3

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

回答

4
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++; 
} 
3
int number = sc.nextInt() 
if(number<0){ 
    neg.add(sc.nextInt()); 
} 
else{ 
    pos.add(sc.nextInt()); 
} 
0

您可以使用導航set ..號碼添加到它,然後就通過傳遞0作爲參數查詢的頭部或尾部。讓我知道你是否想要我詳細說明。

+2

這是一個集合,不會支持雙重條目。如果有人兩次輸入「1」,那麼「1」只會在輸出中出現一次,而不是兩次。這可能不是用戶想要的:) – extraneon

+0

嗯,我同意,雖然根據用例的另一種變化,可以使用導航地圖。其優點是數據結構封裝了存儲數據的用戶邏輯,並減少了用戶代碼中的分支。 – Scorpion