从文件读取后,在数组中添加数字总和

时间:2016-03-10 08:59:14

标签: java arrays int sum file-handling

我试图熟悉文件处理并在创建,编写然后读取文件后计算输入的整数之和。问题出在最后一步,总和将始终打印为最后输入的整数。如何才能使总和正常工作?代码段下方的完整代码以及控制台消息。

     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);

        }

以下是完整的代码:

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!");
        }
   }        

}

3 个答案:

答案 0 :(得分:2)

您的sum = sum+number[i];语句不在循环中,因此您只需将最后一个数字添加到总和中。

你应该在循环内添加总和:

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];
}

答案 1 :(得分:0)

你的总和是在while循环中,所以它不计算在内。使用以下代码修复它:

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!!
}

答案 2 :(得分:0)

试试这个

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!");
            }
       }  
    }