2015-03-13 34 views
0

即時通訊新的數組...我很難理解數組如何在這個代碼中工作... 我正在做一個冒泡排序。唯一我不明白的是變量d可以放在一個變量數組中嗎?爲什麼array [d] 5的值?

import java.util.Scanner; 

    public class bubbleSort 
    { 
    public static void main(String []args) 
    { 
     int n, c, d, swap; 
     Scanner in = new Scanner(System.in); 

     System.out.print("Input number of integers to sort"); 
     n = in.nextInt(); 

     int array[] = new int[n]; 

     System.out.println("Enter " + n + " integers"); 

     for (c = 0; c < n; c++) 
      array[c] = in.nextInt(); 

     for (c = 0; c < (n - 1); c++) 
     { 
       for (d = 0; d < n - c - 1; d++) 
       { 
       if (array[d] > array[d+1]) 
       { 
        System.out.println("array d:" + array[d]); // value is 5 
        swap  = array[d]; 
        array[d] = array[d+1]; 
        array[d+1] = swap; 
       } 
      } 
     } 

     System.out.println("Sorted list of numbers"); 

     for (c = 0; c < n; c++) 
      System.out.println(array[c]); 
} 
} 

回答

1

當它在循環中時,它不是一個變量。那d變量將被分配一個數值。在你的情況下,每一次循環運行d將有從0開始的nc-1值,這將使得數組[0],數組[1] .....所以這將表示爲通過下面的例子: 假設你有一個名爲數組:

int[] array={1,2,3,4,5}; 

所以當你循環使用循環數組:

for (int i = 0; i< 5; i++) 
      system.out.println(array[i]); 
} 

每次循環運行陣列會像

array[0] 
array[1] 
array[2] 
array[3] 
array[4] 

和它打印值等

1 
2 
3 
4 
5 

分別 這表明變量i不被認爲是一個變量而它是一個數值

0

Array的索引是從0開始陣列的長度1。所以索引只能有數值(整數)。 如果你正在做喜歡它下面是不行的(長,浮動,雙

long c=1; 
    int arr[]={1,2,3}; 
    System.out.println(arr[c]);//this will not work as index is long 

,如果你是把可變兼容任何索引INT(短,字節,字符),你會能夠從數組中獲取值。

 int c=1; 
    int arr[]={1,2,3}; 
    System.out.println(arr[c]);// this will work fine and print element at index 1 and that is 2 

對於後面的代碼,輸出將爲2。

相關問題