2015-12-17 79 views
-4

我會發布我的代碼,並希望有人可以告訴要改變什麼做一個「動態數組」?目前的代碼工作,但他們告訴我,這是不正確的方式,而不是我需要做一個動態數組。提前致謝。JAVA動態數組

public static void main(String[] args) { 

int i,a,b; 
int [] array1 = new int[20];//{12,23, -22, 0, 43,545, -4, -55,43, 12,0, -999, -87 

array1[0] = 12; 
array1[1] = 23; 
array1[2] = -22; 
array1[3] = 0; 
array1[4] = 43; 
array1[5] = 545; 
array1[6] = -4; 
array1[7] = -55; 
array1[8] = 43; 
array1[9] = 12; 
array1[10] = 0; 
array1[11] = -999; 
array1[12] = -87; 

int [] arrayPlus = new int[20]; 
int [] arrayMinus = new int[20]; 


a=b=0; 


for (i = 0; i < 13; i++) { 
    if (array1[i] > 0 || array1[i] == 0) { 
     arrayPlus[a] = array1[i]; 
     a++; 
    } else { 
     arrayMinus[b] = array1[i]; 
     b++; 
    } 
} 
System.out.println("Positive array numbers"); 
for (i = 0; i < a; i++) { 
System.out.println(arrayPlus[i]);} 


System.out.println(""); 

System.out.println("Negative array numbers"); 
for (i = 0; i < b; i++) { 
System.out.println(arrayMinus[i]);} 

} 
} 
+0

也許他們要求的是與在運行時可變長度初始化數組?或者也許他們指的是[ArrayLists](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html)?你能告訴我們代碼應該做什麼嗎? – PakkuDon

+0

它必須動態確定數組中的目標數 – exwhy990

+0

另一個學生項目? – aksappy

回答

0

請檢查下面的代碼

 import java.util.Scanner; 
     class DynamicArray { 
     public static void main(String[] args) { 

     int i,a,b; 
     System.out.println("Enter the limit of array :"); 
     Scanner s = new Scanner(System.in); 
     int limit = s.nextInt(); 
     int [] array1 = new int[limit];//{12,23, -22, 0, 43,545, -4, -55,43, 12,0, -999, -87 

     System.out.println("Enter the numbers"); 
     for(i=0; i<limit; i++) 
     { 
      array1[i] = s.nextInt(); 
     } 
     int [] arrayPlus = new int[limit]; 
     int [] arrayMinus = new int[limit]; 


    a=b=0; 


    for (i = 0; i < limit; i++) { 
     if (array1[i] > 0 || array1[i] == 0) { 
       arrayPlus[a] = array1[i]; 
       a++; 
     } else { 
       arrayMinus[b] = array1[i]; 
       b++; 
     } 
    } 
    System.out.println("Positive array numbers"); 
    for (i = 0; i < a; i++) { 
     System.out.println(arrayPlus[i]);} 


     System.out.println(""); 

     System.out.println("Negative array numbers"); 
     for (i = 0; i < b; i++) { 
      System.out.println(arrayMinus[i]);} 

     } 
} 
+0

適合我,但我正在等着看教授說什麼。我回頭告訴你。謝謝你的幫助朋友。 – exwhy990