Home>

I didn't know how to investigate the following problems, so I couldn't move on.
Please teach me.

The variable int num is given the input value from the system.
Declare an ArrayList array variable whose element is an Integer type.
Add the numerical value of the variable int num from 0 to the ArrayList variable as an element.
In addition, please implement using the for statement to add an element.
After processing, use the extended for statement to output the sum of all elements of the ArrayList variable.

01
Input value 10
Expected value 55
02
Input value 100
Expected value 5050
03
Input value 0
Expected value 0

Error message
(1) I don't know how to add elements to an ArrayList using a for statement.
(2) I don't know how to output the sum of elements using an extended for statement
Applicable source code
import java.util.Scanner;
public class Main {
  public static void main (String [] args) {
    Scanner scan = new Scanner (System.in);
    String text = scan.next ();
    int num = Integer.parseInt (text);
    ArrayList<Integer>intList = new ArrayList<Integer>();
  }
}

(1)
for (int i = 0;i intList.add (int num);
}

  • Answer # 1

    import java.util.Scanner;
    import java.util. *;
    public class Main {
      public static void main (String [] args) {
        Scanner scan = new Scanner (System.in);
        String text = scan.next ();
        int num = Integer.parseInt (text);
        ArrayListintList = new ArrayList();
        for (int i = 0;i<= num;i ++) {
            // Add numbers from 0 to the input value to the List
            intList.add (i);
        }
        // final output variable
        int resultNum = 0;
        for (int test: intList) {
            System.out.println (test);
            resultNum + = test;
        }
        System.out.println ("sum:" + resultNum);
      }
    }

    Example output (when the input value is 10)

    0
    1
    2
    Three
    Four
    Five
    6
    7
    8
    9
    Ten
    Sum: 55