0

I was trying to store Name and CGPA of student in a file, but it store only name can somebody help me? Here is my Code...

class Marks {
public static void main(String[] args) {

Here is the main method to calculate CGPA

    ArrayList arrayList = new ArrayList();
    Scanner ed = new Scanner(System.in);
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the name of Students");
    arrayList.add(sc.next());
    System.out.println("Enter number of subjects");
    int n=sc.nextInt();
    double[] marks=new double[n];
    System.out.println("Enter marks of Sub1\t sub2\t sub3\t sub4\t");
    for(int i=0;i<n;i++)
    {
        marks[i]=sc.nextInt();
    }
    double grade[]=new double[n];
    double cgpa,sum=0;
    for(int i=0;i<n;i++)
    {
        grade[i]=(marks[i]/10) ;
    }
    for(int i=0;i<n;i++)
    {
        sum+=grade[i];
    }
    cgpa=sum/n;
    System.out.println("cgpa="+cgpa);
    System.out.println("percentage from cgpa="+cgpa*9.5);

Here is code to write in a file

    try {
        FileWriter fileWriter = new FileWriter("Report.txt");
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()){

            fileWriter.write(iterator.next()+"\n");
        }
        fileWriter.close();
    }catch (IOException e){
        System.out.println("!!!ERROR!!!");

    }
 }

}

Deniss
  • 13
  • 2
  • 1
    You are only calling `arrayList.add` once to add the name. So that you arraylist only contains the names when you save it should come as no surprise to you. Just look at your own code and count the number of times you see `arrayList.add` – OH GOD SPIDERS Feb 10 '21 at 12:46
  • 1
    You should not be using a raw ArrayList. – Jems Feb 10 '21 at 12:46
  • 1
    Also: [You shouldn't use raw types like you do with ArrayList](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – OH GOD SPIDERS Feb 10 '21 at 12:47

2 Answers2

1

You need to capture the calculated CGPA values. Consider using a Map with the student name being the key.

 Map<String,Double> cgpaMap = new HashMap<>();
 List<String> students = new ArrayList<>();
 ... other setup ...

 student = .. get student from input ..
 students.add(student);
 ... other input ...

 cgpa = .. calculate the CGPA ..
 cgpaMap.put(student, cgpa);

Now you can alter the output to include the CGPA by looking up the value in the Map.

 for (Student student : students) {
   fileWriter.write(String.format("%s %f%n", student, cgpaMap.get(student)));
 }
vsfDawg
  • 1,425
  • 1
  • 9
  • 12
0

I think you are not adding CGPA in arraylist after calculating. So when you are writing in file, only name is written.

pratap
  • 538
  • 1
  • 5
  • 11