Salesforce関連の記事を書いています。

  1. Apex練習問題

Exercise 3: Iteration and List Manipulation

Write your code according to the following conditions

  1. Declare a variable numbers of type List and store integers from 1 to 5 in order.
  2. Take each element of numbers in turn, double its value, and output it to the console using System.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

  1. Create a list named numbers (like a box that can store multiple numbers).
  2. Put the numbers from 1 to 5 in that list in order.
  3. Take the numbers in the list one by one and double them.
  4. 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. This Integer means 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 num is 1, then 2, 3, 4, 5, and so on.
  • num * 2: The extracted numbers are doubled by * 2. For example, if 1 is taken out, it is doubled to 2.
  • 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 doubling 1.

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.

Apex練習問題 recent post

  1. Exercise 3: Iteration and List Manipulation

  2. Exercise 1: Variable Declaration and Manipula…

  3. Exercise 2: Conditional Branching and Variabl…

  4. Exercise 4: Combining conditional branches an…

  5. Exercise 5: Filtering and Calculating Lists

関連記事

PAGE TOP