Answer:
The solution code is written in Java.
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.Scanner;
- import java.util.ArrayList;
- public class Main {
- public static void main(String[] args) {
- ArrayList<Integer> nums = new ArrayList<Integer>();
- try {
- File fileObj= new File("numbers.txt");
- Scanner reader = new Scanner(fileObj);
- while (reader.hasNextLine()) {
- String row = reader.nextLine();
- nums.add(Integer.parseInt(row));
- }
- reader.close();
- } catch (FileNotFoundException e) {
- System.out.println("File not found.");
- e.printStackTrace();
- }
- int sum = 0;
- for(int i=1; i <= nums.get(0); i++){
- sum += nums.get(i);
- }
- System.out.println(sum);
- }
- }
Step-by-step explanation:
Firstly, include all the necessary libraries (Line 1 -4).
Next, create an ArrayList object, nums (Line 10).
Next, create a File object to read the numbers from the text file (Line 13) and then create a Scanner object to hold the data read from the text file (Line 14).
Create a while loop to read every row of the number from the text file and add it to nums. (Line 15 - 18)
Create a for loop to traverse through the number taken from the second item of the arrayList and add it to sum variable. (Line 27 -29)
At last, print the sum (Line 30)