1-D arrays: store, index, and traverse · Array 1-D: simpan, indeks, dan jelajahi
Many values in one box
- An array holds many values of the same type in order.
- Until now one variable held one value. An array holds a whole list.
- For example, the test scores of a class can live in one
intarray.
Banyak nilai dalam satu kotak
- Array menyimpan banyak nilai dengan tipe yang sama secara berurutan.
- Sebelumnya satu variabel menyimpan satu nilai. Array menyimpan seluruh daftar.
- Sebagai contoh, nilai ujian siswa dapat disimpan dalam satu array
int.
Make an array with values
- If you know the values, list them in curly braces
{ }. - The type is the element type plus
[], likeint[]. - Java counts how many values you gave and makes the array that size.
Buat array dengan nilai
- Jika Anda mengetahui nilainya, tuliskan dalam kurung kurawal
{ }. - Tipenya adalah tipe elemen ditambah
[], sepertiint[]. - Java menghitung berapa banyak nilai yang Anda berikan dan membuat array dengan ukuran tersebut.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores[0]); // 90
System.out.println(scores[2]); // 70
}
}
Index positions
- Each value has an index (its position). Indexes start at 0.
- So the first value is
scores[0], the second isscores[1], and so on. - You can also change a value:
scores[1] = 85;.
Posisi indeks
- Setiap nilai memiliki indeks (posisinya). Indeks dimulai dari 0.
- Jadi nilai pertama adalah
scores[0], kedua adalahscores[1], dan seterusnya. - Anda juga dapat mengubah nilai:
scores[1] = 85;.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
scores[1] = 85; // change the middle value
System.out.println(scores[1]); // 85
}
}
Make an empty array
- Use
new int[n]to make an array ofnvalues. - Every
intslot starts at 0 automatically. - Then you fill the slots one by one.
Buat array kosong
- Gunakan
new int[n]untuk membuat array berisinnilai. - Setiap slot
intdimulai dari 0 secara otomatis. - Kemudian isi slot-slot tersebut satu per satu.
public class Main {
public static void main(String[] args) {
int[] nums = new int[3]; // {0, 0, 0}
nums[0] = 5;
nums[1] = 6;
System.out.println(nums[0] + " " + nums[1] + " " + nums[2]); // 5 6 0
}
}
.length
array.lengthtells you how many values the array has.- Note: no parentheses — it is
scores.length, notscores.length(). - The last valid index is always
length - 1.
.length
array.lengthmemberi tahu Anda berapa banyak nilai yang ada dalam array.- Catatan: tanpa tanda kurung — ini adalah
scores.length, bukanscores.length(). - Indeks terakhir yang valid selalu
length - 1.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores.length); // 3
System.out.println(scores[scores.length - 1]); // 70 (last value)
}
}
Traverse with a for loop
- To visit every value, loop the index from
0up tolength - 1. - Use
i < array.lengthas the stop test. - Below we add up every value.
Traversing dengan loop for
- Untuk mengunjungi setiap nilai, lakukan loop indeks dari
0hinggalength - 1. - Gunakan
i < array.lengthsebagai tes penghenti. - Di bawah ini kita menjumlahkan setiap nilai.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total = total + scores[i];
}
System.out.println(total); // 240
}
}
Enhanced for loop
- The enhanced for (or "for-each") visits each value directly.
- Read it as: "for each
int vinscores". - Use it when you only need the values, not the index.
Perulangan for Ditingkatkan
- Enhanced for (atau "for-each") mengunjungi setiap nilai secara langsung.
- Bacalah sebagai: "untuk setiap
int vdalamscores". - Gunakan jika Anda hanya membutuhkan nilai, bukan indeks.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int v : scores) {
total = total + v;
}
System.out.println(total); // 240
}
}
Common mistakes
a.lengthhas no(); valid indexes run0toa.length - 1.- Going out of range throws ArrayIndexOutOfBoundsException.
Kesalahan umum
a.lengthtidak memiliki(); indeks valid berjalan dari0hinggaa.length - 1.- Melewati batas akan menyebabkan ArrayIndexOutOfBoundsException.
Now you try
- Some tasks print a result; others complete a method the Harness calls.
- Remember: indexes start at 0, and the last index is
length - 1. - Press Run to compile, then Check answer.
Sekarang Anda coba
- Beberapa tugas mencetak hasil; yang lain menyelesaikan metode yang dipanggil oleh Harness.
- Ingat: indeks dimulai dari 0, dan indeks terakhir adalah
length - 1. - Tekan Run untuk mengkompilasi, lalu Check answer.
A 1-D array, indexed · Array 1-D, berindeks
An array stores values in order; reach one with a[i]. · Array menyimpan nilai secara berurutan; capai satu dengan a[i].
The array nums is already filled. Use a loop to add up all its values and print the total on one line. For {4, 8, 15, 16, 23, 42} the output is 108. · Array nums sudah terisi. Gunakan perulangan untuk menjumlahkan semua nilainya dan cetak totalnya dalam satu baris. Untuk {4, 8, 15, 16, 23, 42} outputnya adalah 108.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Complete sum(int[] a) so it returns the sum of all values in the array. An empty array should return 0. The checker calls it with several arrays. · Lengkapi sum(int[] a) agar mengembalikan jumlah dari semua nilai dalam array. Array kosong harus mengembalikan 0. Pengecek memanggilnya dengan beberapa array.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Complete doubleAll(int[] a). It does not return anything. Instead it changes the array in place so every value becomes twice as big. {1, 2, 3} becomes {2, 4, 6}. · Lengkapi doubleAll(int[] a). Ia tidak mengembalikan apa pun. Sebaliknya, ia mengubah array secara langsung sehingga setiap nilai menjadi dua kali lebih besar. {1, 2, 3} menjadi {2, 4, 6}.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.