【问题标题】:How do i pass a specific content of an index of an arraylist to a method?如何将数组列表索引的特定内容传递给方法?
【发布时间】:2020-12-18 16:41:41
【问题描述】:

如何将数组列表索引的特定内容传递给方法? (我不确定正确的术语)

这就是我想要实现的目标: 获取用户输入的从第一个帐户中提取的金额,然后打印余额。重复 存款也一样。

这是我的课程代码:

import java.util.Date;

public class Account2 {
    private int id = 0;
    private double balance = 0;
    private static double annualInterestRate = 0;
    private Date dateCreated;

    public Account2() {
        id = 0;
        balance = 0;
    }

    public Account2(int id, double balance) {
        this.id = id;
        this.balance = balance;
    }

    // getters and setters (omitted for brevity)

    public double withdraw(int amount) {
        return balance - amount;
    }

    public double deposit(int amount) {
        return balance + amount;
    }
}

这是测试类:

import java.util.ArrayList;
import java.util.Scanner;

public class TestAccount2 {
    public static void main(String[] args) {
        //Account2 acc = new Account2();
        Account2.setannualInterestRate(4.5);
        //Creates an ArrayList of 3 Account objects
        ArrayList<Account2> list = new ArrayList<Account2>();

        for(int i=1; i<4; i++) {
            //USE ARRAYLIST SYNTAX
            list.add(new Account2(i+100, i*10000 ));
        }

        //print all the content of ArrayList
        for(Account2 auto : list) {
            System.out.println(temp);
        }
    
        System.out.println("Enter the amount you'd like to withdraw: ");
        Scanner input = new Scanner(System.in);
        double amount = amount.nextDouble;
        // Get user input for the amount to withdraw from the first account, then print the balance. 
        // Repeat the same for deposit
    }
}

这是我卡住的地方:

        System.out.println("Enter the amount you'd like to withdraw: ");
        Scanner input = new Scanner(System.in);
        double amount = amount.nextDouble;
        // Get user input for the amount to withdraw from the first account, then print the balance. 
        // Repeat the same for deposit

这是我试图将 arraylist 的索引传递到的方法:

public double withdraw(int amount) {
    return balance - amount;
}

谢谢你。

【问题讨论】:

  • 没有完全明白你的意思。您是在尝试调用 ArrayList 中每个帐户的 withdrawdeposit 方法,还是仅在其中一个帐户上调用?
  • @vmaldosan 只有其中之一。我应该指定的,我的错。
  • @nana 你能把它编辑成你的问题吗?

标签: java


【解决方案1】:

您需要调用那些指定要更改的帐户实例的方法。例如,如果你想从 ArrayList 的第一个账户中提现,你会这样写:

list.get(0).withdraw(amount);

您可以对deposit 方法执行相同的操作。

【讨论】:

  • 非常感谢! C:它可以工作,但是withdraw方法不起作用。账户余额不变。有什么原因吗?
  • balance = balance - amount... 您只是返回一个值,而不是更改实例余额
猜你喜欢
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
  • 2013-01-24
相关资源
最近更新 更多