TransWikia.com

Updating Values in ArrayList in Java

Stack Overflow Asked by Billy Dan on January 23, 2021

Trying to update the fees in the ArrayList, once option 3 is selected, one is to input reg no then add fee for that specific student. Once the added fee has be keyed in, the added fee should be added to the initially set fee then update the total fee in the ArrayList. Please help.
When I run my code and add more than one student the initial fee I set for the last student I have entered gets updated yo all the students

Here is my code…

package schoolfinance;

import java.util.*;

public class Student
{
    private final String m_name;
    private final String m_regNo;
    private final String m_course;
    private final String m_year;
    static double m_fees;
    final double total_fees = 50000;
    
    public Student(){
        this("", "", "", "", 0.0);
    }
    
    public Student( String name, String regNo, String course, String year, double fees )
    {
        m_name = name;
        m_regNo = regNo;
        m_course = course;
        m_year = year; 
        m_fees = fees;
    }
     

    public String getName()
    {
        return m_name;
    }

    public String getAge()
    {
        return m_regNo;
    }

    public String getCourse()
    {
        return m_course;
    }

    public String getYear()
    {
        return m_year;
    }

    public double getFees()
    {
        return m_fees;
    }


    public void setFees(Double fees)
    {
       Student.m_fees = fees;
    }


    /**
     *
     * @return
     */
    @Override
    public String toString()
    {
        double balance = total_fees - m_fees;
        return "Name: " + m_name + ",t Reg No: " + m_regNo + 
               ",t Course: " + m_course + ",t Year: " + m_year +
               ",t Fees Paid: " + m_fees + ",t Balance: " + balance;
    }

    public static void main(String[] args) 
    {
       ArrayList<Student> students = new ArrayList<>();
        try (Scanner input = new Scanner(System.in)) {
            int menuChoice = 4;
            do {
                System.out.println("tttStudent Record Menu");
                System.out.println("tt1. Add Studentt2. View Studentst3. Add Feest4. Exit");
                try {
                    System.out.println("Enter a choice: ");
                    menuChoice = Integer.parseInt(input.nextLine());
                } catch (NumberFormatException e) {
                    continue;
                }
                
                if (menuChoice==1)
                {
                    System.out.println("Full name:");
                    String name = input.nextLine();
                    
                    System.out.println("Registration Number:");
                    String regNo = input.nextLine();
                    
                    System.out.println("Course:");
                    String course = input.nextLine();
                    
                    System.out.println("Year:");
                    String year = input.nextLine();
                    
                    float fees = -1;
                    do {
                        try {
                            System.out.println("Fees Paid:");
                            fees = Integer.parseInt(input.nextLine());
                        } catch (NumberFormatException e) {
                            System.out.println("Enter a number!");
                        }
                    } while (fees <= 0);
                    
                    Student student = new Student(name, regNo, course, year, fees);
                    students.add(student);
                    
                } else if (menuChoice==2) {
                    System.out.println("Students:");
                    for (Student student : students){
                        System.out.println(student);
                    }
                } else if (menuChoice==3){
                    Scanner in = new Scanner(System.in);
                    System.out.println("Enter Student Registration Number: ");
                    String id = in.nextLine();
                    students.forEach((Student student) -> {
                        if(student.m_regNo.equals(id)){
                            
                            System.out.println("Found it");
                            System.out.println(student);
                            
                            Scanner new_fee = new Scanner(System.in);
                            System.out.println("Enter Added Fee: ");
                         
                            double added_fee = new_fee.nextFloat();
                            
                            
                            double add_fee = added_fee + m_fees;
                            
                            System.out.println(add_fee);
                            
                            student.setFees(add_fee);
                            
                            
                        } 
                            System.out.println("No Student Record Found Matching that Registration Number!!");
                        
                    });
                    
                }else if (menuChoice < 1 || menuChoice > 4) {
                    System.out.println("Unrecognized Menu Choice, Please re-enter");
                }
            } while (menuChoice != 4);
        }
    }

}

When I run the code and choose option 1, it will prompt for details like full name, reg no, course, year and fee i.e
Full name: Billy Dan
Reg No: BIT100
Course: IT
Year: 3
Fee: 10,000

If I choose option 1 again and add details of another student, the fee value which I’ll insert in the second student will be updated too for the first student which I don’t want.

Now if option 3 is selected, you’ll be prompted for reg no of a particular student you want to update his/her fee. If the reg no is found it will spit out details of that student and then prompt you enter your new fee. So I want when i enter the new fee, the program takes this new fee, adds it to the initial fee then save the total fee as the initial fee.

The program now works fine, though the last fee entered gets updated to the all the other students, for example if my first student had a fee of 5000 then I add another student and insert 7000 as his/her fee, the 7000 will override the 5000 of the first student, so they end up having the same fees

2 Answers

To update the values of your Student objects you need to give the class methods that allow you to do so. You currently only have getters to return the values like

public String getName()
{
    return m_name;
}

What you need to do is add setters for those properties as well eG

public void setName(String name)
{
    this.m_name = name;
}

Note that in order to be able to update the values of your fields you need to remove the final modifier from them!

As the final modifier indicates that a variable cannot be reassigned you need to decide whether to remove them and make the fields not final, or you need to accept the fact that the attributes of your Student class cannot be changed and work with that.

then you can use those setters in your code where you have already found the student object you want to modify:

System.out.println("Found it");
System.out.println(student);

student.setName("some new Name");

Correct answer by OH GOD SPIDERS on January 23, 2021

I m unable to figure out what are you trying to say but it is the simple examples how to update values in ArrayList in java

import java.util.ArrayList;
public class UpdateArrayListValues {
  public static void main(String args[]) {
    ArrayList<Integer> arraylist = new ArrayList<Integer>();
    arraylist.add(1);
    arraylist.add(2);
    arraylist.add(3);
    arraylist.add(4);
    arraylist.add(5);
    arraylist.add(6);
    arraylist.add(7);
    System.out.println("ArrayList before update: "+arraylist);
    //Updating 1st element
    arraylist.set(0, 11);
    //Updating 2nd element
    arraylist.set(1, 22);
    //Updating 3rd element
    arraylist.set(2, 33);
    //Updating 4th element
    arraylist.set(3, 44);
    //Updating 5th element
    arraylist.set(4, 55);
    System.out.println("ArrayList after Update: "+arraylist);
  }
}

Here is the output 
ArrayList before update: [1, 2, 3, 4, 5, 6, 7]
ArrayList after Update: [11, 22, 33, 44, 55, 6, 7]

Answered by Umair Mubeen on January 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP