目次
Write your code according to the following conditions
- Declare a variable
numbers oftypeListand store integers from1to5in order.- Take each element of
numbersin turn, double its value, and output it to the console usingSystem.debug().
Solution Example
// Declare a variable numbers of type List and store integers from 1 to 5
List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};
// take each element of numbers, double its value and output it to the console
for (Integer num : numbers) {
Integer doubledValue = num * 2;
System.debug('Doubled Value: ' doubledValue); Explanation
In this problem, you need to do the following
- Create a list named
numbers(like a box that can store multiple numbers). - Put the numbers from
1to5in that list in order. - Take the numbers in the list one by one and double them.
- The result of the doubling is displayed on the console (a screen that displays the results of the program’s operation).
1. Creating the list numbers
List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};- List: A list is a collection of many numbers or data that can be stored together as one. In this case, we are creating a list of type
List. ThisIntegermeans an integer (a number without a decimal point). - {1, 2, 3, 4,
5}: The list called numbers contains five numbers:1, 2, 3, 4, 5.
2. Extract and process the contents of the list
for (Integer num : numbers) {
Integer doubledValue = num * 2;
System.debug('Doubled Value: ' + doubledValue);
}- for (Integer num : numbers): This is the part where the numbers in the list are taken out one by one in sequence. At first
numis1, then2,3,4,5, and so on. - num * 2: The extracted numbers are doubled by
* 2. For example, if1is taken out, it is doubled to2. - System.debug(‘Doubled Value: ‘ doubledValue): This instruction is used to display the doubled number on the console. For example, it displays
2, the result of doubling1.
3. What is displayed on the console
When this program is executed, the following results are displayed on the console:
Doubled Value: 2
Doubled Value: 4
Doubled Value: 6
Doubled Value: 8
Doubled Value: 10 This is the result of doubling the numbers 1 through 5 in the list.
Point
- List: A list is a collection of numbers or data that can be stored together.
- For loop: Used to retrieve and process the data in a list one by one.
- System.debug(): Instruction to display the result on the console.
