Ask Question
4 June, 05:39

Create a code that reads data from a text file into an ArrayList data structure. It should then sum the numbers and print the sum to the screen. The first number in the file is the number of integers that follows.

+1
Answers (1)
  1. 4 June, 07:00
    0
    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 nums = new ArrayList (); 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); } }

    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)
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Create a code that reads data from a text file into an ArrayList data structure. It should then sum the numbers and print the sum to the ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers