java - 如何将数组列表索引的特定内容传递给方法?
问题描述
如何将数组列表索引的特定内容传递给方法?(我不确定正确的术语)
这就是我想要实现的目标:获取用户输入以从第一个帐户中提取的金额,然后打印余额。对存款重复相同的操作。
这是我的课程代码:
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 的第一个帐户中提取,您将编写如下内容:
list.get(0).withdraw(amount);
您可以对该deposit
方法执行相同的操作。
推荐阅读
- c - 我可以使用字符串作为宏在 C 中传递该宏的值吗?
- javascript - 渲染组件后如何手动更改“选择”的值
- php - PHP从多级标签冒号XML文件DOM PHP中获取数据
- powershell - 如何在powershell中撤销certificatevalidationcallback
- sql - 使用部分索引排除约束 - Postgresql
- node.js - 使用 : 在 json 键中解析 nodejs 中的 json
- node.js - how to access field name in mongoose $aggregate->$lookup-> pipeline->$match
- c# - 带有标题和正文的 SendAsync HttpPost 的困难
- c# - 签名 xml 中数字签名中的时间戳
- javascript - EJS / Mongoose - 帖子在 POST 之后往往会显示两次,当我尝试获取同一页面时,它会显示两次?