gdagis
gdagis

Reputation: 113

Adding sum of numbers in array after reading from a file

I'm trying to familiarize myself with file handling and calculate the sum of entered integers after creating, writing and then reading a file. The issue is in the last step, the sum is always printed as the last entered integer. How can I get the sum working properly? Full code below the snippet, along with the console message.

     public static void readRecords()
   {    
        try (BufferedReader br = new BufferedReader (new FileReader("numbers.txt"))){
            String line;
            int[] number = new int[10];
            int i=-1;
            while ((line = br.readLine()) != null) {
                i++;
                String[] split = line.split(":");
                line = split[1].trim();
                number[i] = Integer.parseInt(line);
                System.out.printf("Integer number %d: %d%n", i, numbers[i]);

            }

            int sum = 0;
            float average;

            sum = sum+number[i];
            System.out.printf("Cool . Your sum is %d%n", sum);

        }

Here's the code in full:

package average;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.SecurityException;
import java.nio.file.NoSuchFileException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.InputMismatchException;




public class Average {

private static Formatter output;

static Scanner input = new Scanner(System.in);
static int[] numbers = new int[10];

public static void main(String[] args)
    {
        openFile();
        addRecords();
        closeFile();
        readRecords();
    //   closeFile();
    }
    public static void openFile()
    {
        try
        {
            output = new Formatter("numbers.txt");
        }
        catch (SecurityException securityException)
        {
            System.err.println("Write permission denied. Terminating.");
            System.exit(1);
        }
        catch (FileNotFoundException fileNotFoundException)
        {
            System.err.println("Error opening file. Terminating.");
            System.exit(1);
        }
    }
    public static void addRecords()
    {   
        System.out.print("Hello, welcome to my program!\n");

        for (int i = 0 ; i < 10 ; i++) {
             System.out.printf("Please enter integer %d: ", i+1);
             numbers[i] = input.nextInt();

             {
                 try
                 {
                    output.format("Inputted integer: %s%n", String.valueOf(numbers[i])); 
                 }
                 catch (FormatterClosedException formatterClosedexception)
                 {
                     System.err.println("Error writing to the file. Terminating.");
                     break;
                 }
                 catch (InputMismatchException inputMismatchException)
                 {
                     System.err.println("Please restart the program and enter integers ONLY.");
                     break;
                 }
                 catch (NoSuchElementException elementException)
                 {
                     System.err.println("Invalid input. Please try again.");
                     input.nextLine();
                 }
             }

         }
    }
    public static void closeFile(){
        {
            if (output != null)
                output.close();
        }
   }
   public static void readRecords()
   {    
        try (BufferedReader br = new BufferedReader (new FileReader("numbers.txt"))){
            String line;
            int[] number = new int[10];
            int i=-1;
            while ((line = br.readLine()) != null) {
                i++;
                String[] split = line.split(":");
                line = split[1].trim();
                number[i] = Integer.parseInt(line);
                System.out.printf("Integer number %d: %d%n", i, numbers[i]);

            }

            int sum = 0;
            float average;

            sum = sum+number[i];
            System.out.printf("Cool . Your sum is %d%n", sum);

        }
        catch (NoSuchFileException noSuchFileException)
        {
            System.out.print("This file was not created properly and cannot be found.");
        }
        catch (FileNotFoundException fileNotFoundException) 
        {
            System.out.print("I can't seem to find your file :( That's too bad...");
        } 
        catch (IOException ioexception) 
        {
            System.out.print("Whoopsie daisy, you got yourself an IOException. Better luck next time!");
        }
        finally
        {
            System.out.print("Check your numbers.txt file and see what ya got!");
        }
   }        

}

Upvotes: 0

Views: 1871

Answers (3)

Nikolas
Nikolas

Reputation: 44398

Your sum addition is out the while-loop, so it won't count. Fix it with the following code:

int sum=0 ;
while ((line = br.readLine()) != null) {
   i++;
   String[] split = line.split(":");
   line = split[1].trim();
   number[i] = Integer.parseInt(line);
   System.out.printf("Integer number %d: %d%n", i, numbers[i]);
   sum+=number[i]; // Here!!
}

Upvotes: 0

P S M
P S M

Reputation: 1161

Try this

import java.util.Scanner;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.lang.SecurityException;
    import java.nio.file.NoSuchFileException;
    import java.util.Formatter;
    import java.util.FormatterClosedException;
    import java.util.NoSuchElementException;
    import java.util.InputMismatchException;




    public class Test {

    private static Formatter output;

    static Scanner input = new Scanner(System.in);
    static int[] numbers = new int[10];

    public static void main(String[] args)
        {
            openFile();
            addRecords();
            closeFile();
            readRecords();
        //   closeFile();
        }
        public static void openFile()
        {
            try
            {
                output = new Formatter("numbers.txt");
            }
            catch (SecurityException securityException)
            {
                System.err.println("Write permission denied. Terminating.");
                System.exit(1);
            }
            catch (FileNotFoundException fileNotFoundException)
            {
                System.err.println("Error opening file. Terminating.");
                System.exit(1);
            }
        }
        public static void addRecords()
        {   
            System.out.print("Hello, welcome to my program!\n");

            for (int i = 0 ; i < 3 ; i++) {
                 System.out.printf("Please enter integer %d: ", i+1);
                 numbers[i] = input.nextInt();

                 {
                     try
                     {
                        output.format("Inputted integer: %s%n", String.valueOf(numbers[i])); 
                     }
                     catch (FormatterClosedException formatterClosedexception)
                     {
                         System.err.println("Error writing to the file. Terminating.");
                         break;
                     }
                     catch (InputMismatchException inputMismatchException)
                     {
                         System.err.println("Please restart the program and enter integers ONLY.");
                         break;
                     }
                     catch (NoSuchElementException elementException)
                     {
                         System.err.println("Invalid input. Please try again.");
                         input.nextLine();
                     }
                 }

             }
        }
        public static void closeFile(){
            {
                if (output != null)
                    output.close();
            }
       }
       public static void readRecords()

       {    
           int sum = 0;
           try (BufferedReader br = new BufferedReader (new FileReader("numbers.txt"))){
                String line;
                int[] number = new int[10];
                int i=-1;
                while ((line = br.readLine()) != null) {
                    i++;
                    String[] split = line.split(":");
                    line = split[1].trim();
                    number[i] = Integer.parseInt(line);
                    System.out.printf("Integer number %d: %d%n", i, numbers[i]);

                }


                float average;
                for(int k : number){
                sum = sum+k;}
                System.out.printf("Cool . Your sum is %d%n", sum);

            }
            catch (NoSuchFileException noSuchFileException)
            {
                System.out.print("This file was not created properly and cannot be found.");
            }
            catch (FileNotFoundException fileNotFoundException) 
            {
                System.out.print("I can't seem to find your file :( That's too bad...");
            } 
            catch (IOException ioexception) 
            {
                System.out.print("Whoopsie daisy, you got yourself an IOException. Better luck next time!");
            }
            finally
            {
                System.out.print("Check your numbers.txt file and see what ya got!");
            }
       }  
    }

Upvotes: 0

Eran
Eran

Reputation: 393841

Your sum = sum+number[i]; statement is outside the loop, so you only add the last number to the sum.

You should add to the sum inside the loop :

int sum = 0;
while ((line = br.readLine()) != null) {
    i++;
    String[] split = line.split(":");
    line = split[1].trim();
    number[i] = Integer.parseInt(line);
    System.out.printf("Integer number %d: %d%n", i, numbers[i]);
    sum += number[i];
}

Upvotes: 2

Related Questions