Ask Question
2 February, 21:12

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.

+2
Answers (1)
  1. 3 February, 01:07
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers