更新Java中ArrayList中的值

huangapple go评论43阅读模式
英文:

Updating Values in ArrayList in Java

问题

以下是您要翻译的内容:

尝试在ArrayList中更新费用,一旦选择选项3,就需要输入注册号,然后为特定学生添加费用。一旦添加了费用,应将添加的费用添加到最初设置的费用中,然后更新ArrayList中的总费用。请帮忙。
当我运行我的代码并添加多个学生时,我为最后一个输入的学生设置的初始费用会更新到所有学生。

这是我的代码...

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("\t\t\tStudent Record Menu");
                System.out.println("\t\t1. Add Student\t2. View Students\t3. Add Fees\t4. 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);
        }
    }

}

当我运行代码并选择选项1时,它会提示输入完整姓名、注册号、课程、年份和费用,例如:
完整姓名:Billy Dan
注册号:BIT100
课程:IT
年级:3
费用:10,000

如果我再次选择选项1并添加另一个学生的详细信息,我将插入到第二个学生的费用值也会更新到第一个学生,这是我不想要的。
如果选择选项3,您将被提示输入要更新其费用的特定学生的注册号。如果找到注册号,它将显示该学生的详细信息,然后提示您输入新费用。因此,我希望当我输入新费用时,程序将接受这个新费用,将其添加到初始费用中,然后将总费用保存为初始费用。
该程序现在运行正常,尽管最后输入的费用会更新到所有其他学生,例如,如果我的第一个学生的费用为5000,然后我添加另一个学生并插入7000作为他/她的费用,那么7000将覆盖第一个学生的5000,因此他们最终会具有相同的费用。

英文:

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(&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, 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 &quot;Name: &quot; + m_name + &quot;,\t Reg No: &quot; + m_regNo + 
&quot;,\t Course: &quot; + m_course + &quot;,\t Year: &quot; + m_year +
&quot;,\t Fees Paid: &quot; + m_fees + &quot;,\t Balance: &quot; + balance;
}
public static void main(String[] args) 
{
ArrayList&lt;Student&gt; students = new ArrayList&lt;&gt;();
try (Scanner input = new Scanner(System.in)) {
int menuChoice = 4;
do {
System.out.println(&quot;\t\t\tStudent Record Menu&quot;);
System.out.println(&quot;\t\t1. Add Student\t2. View Students\t3. Add Fees\t4. Exit&quot;);
try {
System.out.println(&quot;Enter a choice: &quot;);
menuChoice = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
continue;
}
if (menuChoice==1)
{
System.out.println(&quot;Full name:&quot;);
String name = input.nextLine();
System.out.println(&quot;Registration Number:&quot;);
String regNo = input.nextLine();
System.out.println(&quot;Course:&quot;);
String course = input.nextLine();
System.out.println(&quot;Year:&quot;);
String year = input.nextLine();
float fees = -1;
do {
try {
System.out.println(&quot;Fees Paid:&quot;);
fees = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
System.out.println(&quot;Enter a number!&quot;);
}
} while (fees &lt;= 0);
Student student = new Student(name, regNo, course, year, fees);
students.add(student);
} else if (menuChoice==2) {
System.out.println(&quot;Students:&quot;);
for (Student student : students){
System.out.println(student);
}
} else if (menuChoice==3){
Scanner in = new Scanner(System.in);
System.out.println(&quot;Enter Student Registration Number: &quot;);
String id = in.nextLine();
students.forEach((Student student) -&gt; {
if(student.m_regNo.equals(id)){
System.out.println(&quot;Found it&quot;);
System.out.println(student);
Scanner new_fee = new Scanner(System.in);
System.out.println(&quot;Enter Added Fee: &quot;);
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(&quot;No Student Record Found Matching that Registration Number!!&quot;);
});
}else if (menuChoice &lt; 1 || menuChoice &gt; 4) {
System.out.println(&quot;Unrecognized Menu Choice, Please re-enter&quot;);
}
} 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

答案1

得分: 0

以下是您要翻译的内容:

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

英文:

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&lt;Integer&gt; arraylist = new ArrayList&lt;Integer&gt;();
arraylist.add(1);
arraylist.add(2);
arraylist.add(3);
arraylist.add(4);
arraylist.add(5);
arraylist.add(6);
arraylist.add(7);
System.out.println(&quot;ArrayList before update: &quot;+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(&quot;ArrayList after Update: &quot;+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]

答案2

得分: 0

要更新您的学生对象的值,您需要提供类方法来实现这样做。目前,您只有用于返回值的getter方法,例如:

public String getName()
{
    return m_name;
}

您需要做的是为这些属性添加setter方法,例如:

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

请注意,为了能够更新字段的值,您需要从它们中删除final修饰符!

因为final修饰符表示变量无法被重新赋值,您需要决定是删除它们并使字段非final,还是接受您的Student类的属性无法更改这一事实,并与之一起工作。

然后,您可以在已经找到要修改的学生对象的代码中使用这些setter方法:

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

student.setName("some new Name");
英文:

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(&quot;Found it&quot;);
System.out.println(student);
student.setName(&quot;some new Name&quot;);

huangapple
  • 本文由 发表于 2020年7月31日 18:15:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63189932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定