iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0
JavaScript

大樂透對獎系列 第 7

陣列

  • 分享至 

  • xImage
  •  

陣列基本上是用來收集資料,是具有索引(Index)的資料結構

int[] scores = {88, 81, 78, 76, 85};

這個程式片段建立了一個陣列,因為使用int[]宣告,記憶體會分配長度為5的int連續空間,各個空間儲存了88、81、78、76、85,各個空間都給予索引編號,索引由 0開始,由於長度是5,最後一個索引為4,如果存取超出索引範圍,就會拋出ArrayIndexOutOfBoundsException的錯誤。

若想要循序地取出陣列中每個值,可以使用for迴圈:

package cc.openhome;

public class Score {
public static void main(String[] args) {
int[] scores = {88, 81, 78, 76, 85};
for(var i = 0; i < scores.length; i++) {
System.out.printf("學生分數:%d %n", scores[i]);
}
}
}

在宣告的參考名稱旁加上[]並指定索引,就可以取得對應值,上例從i為0到4,逐一取得值並顯示出來。

結果如下:

學生分數:88
學生分數:81
學生分數:78
學生分數:76
學生分數:85


上一篇
基本型態包裹器
下一篇
陣列
系列文
大樂透對獎13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言