首页 > 解决方案 > How to store values in an array and save them in a file

问题描述

This is my part of my code. Basically I am trying to store the values from double Avg and char gradeLetter in the arrays doubleAVG and charGRADE. What im getting so far is that on the first loop, lets say Avg = 2 then that will be a stored in the file, but if there is a second loop and the value of Avg changes to 3 then 3 will be saved in the file twice. It deletes 2 and saves the number 3 twice. How can i fix that? I want the first loop to store the first value of Avg that can be 2 and then on the second loop to store the new value of Avg that could be 3 but without overwriting the 2. IGNORE THE COMMENTS.

    try {
        FileWriter fw = new FileWriter(fileN);

        for (int count = 0; count < students; count++) {

            doubleAVG = new double[students];
            charGRADE = new char[students];

            doubleAVG[count] = Avg;
            charGRADE[count] = gradeLetter;

            fw.write("This is the grade of: " + FirstName + " " + LastName
                    + " ");
            fw.write(String.valueOf(doubleAVG[count]) + " ");
            fw.write(charGRADE[count]);
        }
        fw.close();
    } catch (Exception e) {
        System.out.println(e);
    }

标签: java

解决方案


请将您的代码修改为:

public class Main {

    public static void main(String[] args) {
        try {
            FileWriter fw = new FileWriter(new File("F://test.txt"));
            Scanner sc = new Scanner(System.in);
            int students = 2;
            double[] doubleAVG = new double[students];
            char[] charGRADE = new char[students];
            double avg = 0.0;
            char gradeLetter;
            String FirstName = "";
            String LastName = "";
            for (int count = 0; count < students; count++) {
                System.out.println("Enter average :");
                avg = sc.nextDouble();
                System.out.println("Enter grade :");
                gradeLetter = sc.next().charAt(0);
                System.out.println("Enter First Name :");
                FirstName = sc.next();
                System.out.println("Enter Last Name :");
                LastName = sc.next();
                doubleAVG[count] = avg;
                charGRADE[count] = gradeLetter;
                fw.write("This is the grade of: " + FirstName + " " + LastName + " ");
                fw.write(String.valueOf(doubleAVG[count]) + " ");
                fw.write(charGRADE[count] + System.lineSeparator());
            }
            fw.close();
            sc.close();
        } catch (Exception e) {
            System.out.println(e);
        }

    }

}

控制台输入:

Enter average :
70.45
Enter grade :
B
Enter First Name :
John 
Enter Last Name :
Johnson
Enter average :
90.47
Enter grade :
A
Enter First Name :
Michael 
Enter Last Name :
Jordan

test.txt中:

This is the grade of: John Johnson 70.45 B
This is the grade of: Michael Jordan 90.47 A

推荐阅读