คืนค่าการตั้งค่าทั้งหมด
คุณแน่ใจว่าต้องการคืนค่าการตั้งค่าทั้งหมด ?
ลำดับตอนที่ #7 : Java II - Arrays
Using
Arrays
Arrays
An array is a set of variables. It can manage multiple
pieces of data, like a list
of names, instead of declaring them separately. Each value in an array
is called an element.
Array
Data Types
When declaring a variable for an
array, you have to put [] after the type of
each element. For example, an array of int values would be type int[]
, and an array of String
values would be type String[] .
Creating
Arrays
You can make arrays by writing values
in { } and separating them with commas , . Check the example below. Be careful not to
confuse [] and {}.
The
Index Number
Each element of an array is given a
number like 0, 1,
2, ... . These
are called index numbers.
Keep in mind that index numbers start from 0.
You can access individual elements by writing array_name[index]
.
Updating
the Elements of Arrays
Let's also try updating an element of
an array! Each element in an array is a value, so you can update it by
assigning a different value to it.
When
the Element Doesn't Exist
You can't assign a value to an element
that doesn't exist. It will result in an error, like in the example below!
Arrays
and Loops
When dealing with arrays, we often
want to apply the same code to each element. You can easily do this with the
loops we learned earlier. So, let's learn how to use loops with arrays!
Arrays
and For Loops
When you want to print all the
elements of an array, it's not efficient to repeat the same code like in the
left image. By using a for loop, like the right image, you can easily get the
value of each element and print it.
Length
of an Array
You can use length
to count the number of elements in an array, like the example on the left. By
using length, you can replace i < 3 with i < names.length, like shown on the right. This
way you don't need to count the number of elements yourself.
Enhanced
For Loops
The enhanced for loop is a special type of for loop used with arrays. It's
just a simpler way of writing for loops. See the example below for the syntax
of an enhanced for loop!
How
Enhanced For Loops Work
The enhanced for loop only requires a
temporary variable in which every single element of the array is assigned one
by one. In the example below, each element of the names
array is assigned to the name
variable, and then gets printed.
Comparison
of For Loops
Let's practice changing a standard for loop to an
enhanced for loop. We used index
numbers to get the elements in a standard for loop, but with enhanced
for loops we can get the elements directly. Remember how to use enhanced for
loops to make your code simpler!
The
Final Project
By using what we've learned so far, let's
calculate the sum of odd
numbers and the sum
of even numbers in an array of integers.
ความคิดเห็น