下面是我的代码,我想创建一个Linkedlist,其中包含来自用户的输入。用户已将值输入到LinkedList(帐户)中。然后,他可以在LinkedList中搜索这些值,如果他输入的那些值(帐户名称)与linkedList中的值相匹配,那么该值将成为所选的新帐户。
如何完成选择方法。
import java.util.*;
public class Customer {
public static void main(String[] args) {
new Customer();
}
private LinkedList<Account> accounts = new LinkedList<Account>();
public Customer() {
setup();
}
private void setup() {
accounts.add(new Account("",0.0));
accounts.add(new Account("",0.0));
accounts.add(new Account("",0.0));
}
public void use() {
char choice;
while((choice = readChoice()) != 'x') {
switch(choice) {
case 'a': choose(); break;
case 'i': addInterest(); break;
case 's': show(); break;
default: help();
}
}
}
private char readChoice() {
return 'x';
}
private void choose() {
for (Account account: accounts) {
}
}
private String readName() {
System.out.print("??? account ???; ");
return In.nextLine();
}
private Account account(String name) {
return null;
}
private void addInterest() {
for (Account account: accounts) {
for (int i = 0; i < 30; i++)
account.addDailyInterest();
account.addMonthlyInterest();
}
}
private void help() {
String s = "The menu choices are";
s += "\n a: choose an account";
s += "\n i: add interest to all accounts";
s += "\n s show";
s += "\n x exit";
System.out.println(s);
}
private void show() {
System.out.println(this);
}
public String toString() {
String s = "";
return s;
}
}
答案 0 :(得分:0)
据我了解您的问题逻辑,您希望能够按名称选择帐户并将其设置为当前帐户。为此,您需要在Customer
类中添加一个成员来存储此选定的Account
,例如
Account selected; // null by default
然后choose()
方法应遍历所有帐户以查找匹配项:
void choose(String name) {
Account found = null;
for (Account acc : accounts) {
if (acc.getName().equals(name)) {
found = acc;
}
}
if (found) {
selected = found;
}
else {
System.out.println(name + " not found in list.");
}
作为建议,您可以show()
显示所选内容(如果存在)的帐户信息,以及可显示所有帐户的showAll()
。
您还需要正确初始化accounts
列表并在main()
中编写逻辑。