Форум

Data.BG Форуми: Клас Account - проблем с методите withdraw и deposit - Data.BG Форуми

Прехвърляне към съдържание

Страница 1 от 1
  • Вие не можете да започнете нова тема
  • Вие не може да отговаряте на тази тема

Клас Account - проблем с методите withdraw и deposit

#1
Потребителят е неактивен   Eyzebio 

  • Група: Потребители
  • Мнения: 49
  • Регистриран: 25-July 09
  • Репутация: 2
Здравейте, отново! Пак имам питане, този път по тази задача. Проблемът ми е свързан с методите withdraw и deposit. В момента увеличава и намалява баланса по сметката на всички в системата. Как да го редактирам така, че да увеличава баланса само по сметката на конкретния потребител :)?


public class Credetials {
private String username;
private String password;

public Credetials() {

}

public Credetials(String username, String password) {
this.setUserName(username);
this.setPassword(password);
}

public String getUserName() {
return username;
}
public void setUserName(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

import java.math.BigDecimal;
import task1.Credentials;

public class Account {
private String clientName;
private long getGovernmentId;
private double accountBalance;
private Credetials credetials;

public Account() {

}

public Account(String clientName, long getGovernmentId,
double accountBalance, String userName,
String password, Credetials credetials) {
this.setClientName(clientName);
this.setGovId(getGovernmentId);
this.setAccountBalance(accountBalance);
this.setCredetials(credetials);
this.credetials.setUserName(userName);
this.credetials.setPassword(password);
}

public double getAccountBalance() {
return accountBalance;
}

public void setAccountBalance(double accountBalance) {
this.accountBalance = accountBalance;
}

public Credetials getCredetials() {
return credetials;
}

public void setCredetials(Credetials credetials) {
this.credetials = credetials;
}

public String getClientName() {
return clientName;
}

public void setClientName(String clientName) {
this.clientName = clientName;
}

public long getGovernmentId() {
return getGovernmentId;
}

public void setGovId(long getGovernmentId) {
this.getGovernmentId = getGovernmentId;
}

public void deposit(int amount) {
if(amount > 0) {
accountBalance = this.getAccountBalance() + amount;
}else {
System.out.println("I won't take this amount");
}
}

public void withdraw(int amount) {
if(amount > 0 && this.getAccountBalance() >= amount) {
accountBalance = this.getAccountBalance() - amount;
}else {
System.out.println("You don't have enough money in your account");
}
}

public boolean hasAccess(String password) {
if(this.getCredetials().getPassword().equalsIgnoreCase(password)) {
return true;
}else {
return false;
}
}

public double getBalance() {
return this.getAccountBalance();
}

public long getGovId() {
return this.getGovId();
}

public String getName() {
return this.getCredetials().getUserName();
}
}

package task2;

import java.util.List;

public class Bank {
private List<Account> accounts;
private Account account;
private Credetials credetials;

public Bank() {

}

public Bank(List<Account> accounts, Account account, Credetials credetials) {
this.setAccounts(accounts);
this.setAccount(account);
this.setCredetials(credetials);
}
public List<Account> getAccounts() {
return accounts;
}

public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}

public Account getAccount() {
return account;
}

public void setAccount(Account account) {
this.account = account;
}

public Credetials getCredetials() {
return credetials;
}

public void setCredetials(Credetials credetials) {
this.credetials = credetials;
}

public void openAccount(String clientName, long governmentId, String username, String password) {
clientName = account.getClientName();
governmentId = account.getGovernmentId();
username = credetials.getUserName();
password = credetials.getPassword();
double accountBalance = account.getAccountBalance();
System.out.printf("Openning new account for %s %d", clientName, governmentId);
System.out.println();
accounts.add(new Account(clientName, governmentId, accountBalance, username, password, credetials));
for(Account acc : accounts) {
System.out.println(acc.getClientName() + " " +
acc.getGovernmentId() + " " +
acc.getAccountBalance() + " " +
acc.getCredetials().getUserName() + " " +
acc.getAccountBalance() + " " +
acc.getCredetials().getPassword());
}
}

public void closeAccount(String username, String password) {
for(int index = 0; index < accounts.size(); index++) {
if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username) &&
accounts.get(index).getCredetials().getPassword().equalsIgnoreCase(password)) {
accounts.remove(index);
System.out.printf("Closing and deleting account with number %d",
accounts.get(index).getGovernmentId());
System.out.println();
}
}
}

public void deposit(String username, int amount) {
for(int index = 0; index < accounts.size(); index++) {
if(amount > 0) {
if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username)) {
accounts.get(index).deposit(amount);
System.out.println("The new amount is now" + accounts.get(index).getAccountBalance());
}
}else {
System.out.println("Invalid amount!");
}
}
}

public void withdraw(String username, String password, int amount) {
for(int index = 0; index < accounts.size(); index++) {
if(amount > 0 && accounts.get(index).getAccountBalance() > 0) {
if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username) &&
accounts.get(index).getCredetials().getPassword().equalsIgnoreCase(password)) {
accounts.get(index).withdraw(amount);
}
}else {
System.out.println("You don't have enough money in your account");
}

}
}

public void transfer(String username, int amount, Account receipient) {
for(int index = 0; index < accounts.size(); index++) {
if(amount > 0 && accounts.get(index).getAccountBalance() > 0) {
if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username)) {
accounts.get(index).setAccountBalance(accounts.get(index).getAccountBalance() - amount);
System.out.println("The balance now is" + accounts.get(index).getAccountBalance());
}
if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(receipient. getCredetials().getUserName())) {
accounts.get(index).setAccountBalance(accounts.get(index).getAccountBalance() + amount);
System.out.println("The balance now is" + accounts.get(index).getAccountBalance());
}
}else {
System.out.println("Invalid amount!");
}
}
}

public double calculateAccountAssets() {
double accountAssets = 0;
for(Account account : accounts) {
accountAssets = accountAssets + account.getAccountBalance();
}
System.out.println("The current balance of the accounts Assets is" + accountAssets);
return accountAssets;
}
}
package task2;

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

import javax.swing.plaf.InputMapUIResource;

public class BankManagementMain {

public static void main(String[] args) {
List<Account> bankAccounts = new ArrayList<>();
Account account = new Account();
Bank bank = new Bank();
Credetials credetials = new Credetials();
Scanner scanner = new Scanner(System.in);

while(true) {
System.out.println("OPEN, CLOSE, DEPOSIT, WITHDRAW, TRANSFER, CheckAssets, END");
String inpuUserCommand = scanner.next();
if(inpuUserCommand.equalsIgnoreCase("END")) {
break;
}
System.out.println("Name");
String clientName = scanner.next();
account.setClientName(clientName);
System.out.println("id");
int governmentId = scanner.nextInt();
account.setGovId(governmentId);
System.out.println("username");
String username = scanner.next();
credetials.setUserName(username);
System.out.println("password");
String password = scanner.next();
credetials.setPassword(password);
account.setCredetials(credetials);
bank.setAccounts(bankAccounts);
bank.setAccount(account);
bank.setCredetials(credetials);
if(inpuUserCommand.equalsIgnoreCase("OPEN")) {
bank.openAccount(clientName, governmentId, username, password);
}else if(inpuUserCommand.equalsIgnoreCase("CLOSE")) {
bank.closeAccount(username, password);
}else if(inpuUserCommand.equalsIgnoreCase("DEPOSIT")) {
System.out.println("Please enter an an amount to deposit");
int amount = scanner.nextInt();
bank.deposit(username, amount);
}else if(inpuUserCommand.equalsIgnoreCase("WITHDRAW")) {
System.out.println("Please enter an an amount to withdraw");
int amount = scanner.nextInt();
bank.withdraw(username, password, amount);
}else if(inpuUserCommand.equalsIgnoreCase("TRANSFER")) {
System.out.println("Please enter an an amount to transfer");
int amount = scanner.nextInt();
Account receiptient = new Account();
Credetials cr = new Credetials();
System.out.println("Name");
String transferName = scanner.next();
receiptient.setClientName(transferName);
System.out.println("id");
int transferId = scanner.nextInt();
receiptient.setGovId(transferId);
System.out.println("username");
String transferNamme = scanner.next();
cr.setUserName(transferNamme);
System.out.println("password");
String tranferPass = scanner.next();
cr.setPassword(tranferPass);
}else if(inpuUserCommand.equalsIgnoreCase("CheckAssets")){
bank.calculateAccountAssets();
}else {
System.out.println("Unknown command");
}
}
}
}
0

#2
Потребителят е неактивен   brigadier 

  • Група: Потребители
  • Мнения: 1102
  • Регистриран: 25-December 05
  • Репутация: 248
По всички не намалява, понеже имаш само един и го презаписваш

За начало може да промениш малко:

public class BankManagementMain {

public static void main(String[] args) {
//List<Account> bankAccounts = new ArrayList<>();
//Account account = new Account();
Bank bank = new Bank();
//Credetials credetials = new Credetials();
Scanner scanner = new Scanner(System.in);

while(true) {
System.out.println("OPEN, CLOSE, DEPOSIT, WITHDRAW, TRANSFER, CheckAssets, END");
String inpuUserCommand = scanner.next();
if(inpuUserCommand.equalsIgnoreCase("END")) {
break;
}
System.out.println("Name");
String clientName = scanner.next();
//account.setClientName(clientName);
System.out.println("id");
int governmentId = scanner.nextInt();
//account.setGovId(governmentId);
System.out.println("username");
String username = scanner.next();
//credetials.setUserName(username);
System.out.println("password");
String password = scanner.next();
//credetials.setPassword(password);
//account.setCredetials(credetials);
//bank.setAccounts(bankAccounts);
//bank.setAccount(account);
//bank.setCredetials(credetials);

===========
public class Bank {
private List<Account> accounts = new ArrayList<>();

//account и credetials са излишни в класа
private Account account;
private Credetials credetials;

public Bank() {

}

public Bank(List<Account> accounts, Account account, Credetials credetials) {
//this.setAccounts(accounts);
//this.setAccount(account);
//this.setCredetials(credetials);
this.accounts = accounts;
this.account = account;
this.credetials = credetials;
}

.......................................

public void openAccount(String clientName, long governmentId, String username, String password) {
//clientName = account.getClientName();
//governmentId = account.getGovernmentId();
//username = credetials.getUserName();
//password = credetials.getPassword();
//double accountBalance = account.getAccountBalance();
System.out.printf("Openning new account for %s %d", clientName, governmentId);
System.out.println();
//accounts.add(new Account(clientName, governmentId, accountBalance, username, password, credetials));
accounts.add(new Account(clientName, governmentId, 0.0, username, password, credetials));

=================================

public class Account {
private String clientName;
private long getGovernmentId;
private double accountBalance;
private Credetials credetials;

public Account() {

}

public Account(String clientName, long getGovernmentId,
double accountBalance, String userName,
String password, Credetials credetials) {
//this.setClientName(clientName);
//this.setGovId(getGovernmentId);
//this.setAccountBalance(accountBalance);
//this.setCredetials(credetials);
//this.credetials.setUserName(userName);
//this.credetials.setPassword(password);

this.clientName = clientName;
this.getGovernmentId = getGovernmentId;
this.accountBalance = accountBalance;
this.credetials = new Credetials(userName, password);
}

...................................

//public double getBalance() {
//return this.getAccountBalance();
//}
//
//public long getGovId() {
//return this.getGovId();
//}
//
//public String getName() {
//return this.getCredetials().getUserName();
//}

И Transfer няма да ти работи, но като стигнеш дотам, ще си го оправиш
0

#3
Потребителят е неактивен   Eyzebio 

  • Група: Потребители
  • Мнения: 49
  • Регистриран: 25-July 09
  • Репутация: 2
Ясно! Трябва да гледам къде ги създавам тези обекти от класа :). Направих както ми каза и сега работят без проблем withdraw и deposit. Ще го гледам по-късно и transfer. Просто преместих Account account = new Account(); в безкрайния цикъл. Хубаво е, че има все още хора, които да ти помогнат!
0

#4
Потребителят е неактивен   Eyzebio 

  • Група: Потребители
  • Мнения: 49
  • Регистриран: 25-July 09
  • Репутация: 2
Пооправих си методите withdraw и deposit, но с transfer все още имам проблем. Проблемът се състои в това, че например вземам 200 долара от единия акаунт (което е ок), но вместо да му даде 200 долара на другия му дава 400... Така изглежда кода на transfer в момента:

public void transfer(String username, int amount, String receipient) {
for (int index = 0; index < accounts.size(); index++) {
if (accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username)) {
if (amount >= 0 && accounts.get(index).getAccountBalance() > 0) {
accounts.get(index).withdraw(amount);
System.out.println("The new balance is now " + accounts.get(index).getAccountBalance());
continue;
} else {
System.out.println("You don't have enough money in your account");
}
}
if (accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(receipient)) {
accounts.get(index).deposit(amount);
System.out.println("The balance now is " + accounts.get(index).getAccountBalance());
}
}
}


в main метода при избиране на клауза transfer съм задал това:
}else if(inpuUserCommand.equalsIgnoreCase("TRANSFER")) {
System.out.println("Enter amount to transfer");
int amount = scanner.nextInt();
String acc1 = null;
String acc2 = null;
System.out.println("Enter receipient");
String receipent = scanner.next();
for (int index = 0; index < bankAccounts.size(); index++) {
if (bankAccounts.get(index).getCredetials().getUserName()
.equalsIgnoreCase(account.getCredetials().getUserName())) {
acc1 = bankAccounts.get(index).getCredetials().getUserName();
}
if( bankAccounts.get(index).getCredetials().getUserName().equalsIgnoreCase(receipent)) {
acc2 = bankAccounts.get(index).getCredetials().getUserName();

}
bank.transfer(acc1, amount, acc2);
}
}

Като цяло този клас за мен за оказа много проблемен, защото надмина доста като обем написаното дотук и ми е много трудно да си проследя написаната логика.

Мнението беше редактирано от Eyzebio: 14.10.16 - 00:21

0

#5
Потребителят е неактивен   brigadier 

  • Група: Потребители
  • Мнения: 1102
  • Регистриран: 25-December 05
  • Репутация: 248
Логиката като цяло е, че в началото правиш една банка с празен списък акаунти и след това, в зависимост от подаденото от конзолата добавяш / вадиш акаунт или суми

Трябва някои неща да се пренаредят:

while(true) {
System.out.println("OPEN, CLOSE, DEPOSIT, WITHDRAW, TRANSFER, CheckAssets, END");
String inpuUserCommand = scanner.next();
if(inpuUserCommand.equalsIgnoreCase("END")) {
break;
}
System.out.println("Name");
String clientName = scanner.next();
//account.setClientName(clientName);
System.out.println("id");
int governmentId = scanner.nextInt();
//account.setGovId(governmentId);
System.out.println("username");
String username = scanner.next();
//credetials.setUserName(username);
System.out.println("password");
String password = scanner.next();
//credetials.setPassword(password);
//account.setCredetials(credetials);
//bank.setAccounts(bankAccounts);
//bank.setAccount(account);
//bank.setCredetials(credetials);
if(inpuUserCommand.equalsIgnoreCase("OPEN")) {
bank.openAccount(clientName, governmentId, username, password);
}else if(inpuUserCommand.equalsIgnoreCase("CLOSE")) {
bank.closeAccount(username, password);
}else if(inpuUserCommand.equalsIgnoreCase("DEPOSIT")) {
System.out.println("Please enter an an amount to deposit");
int amount = scanner.nextInt();
//bank.deposit(username, amount);
bank.deposit(clientName, amount);
}else if(inpuUserCommand.equalsIgnoreCase("WITHDRAW")) {
System.out.println("Please enter an an amount to withdraw");
int amount = scanner.nextInt();
bank.withdraw(username, password, amount);
}else if(inpuUserCommand.equalsIgnoreCase("TRANSFER")) {
System.out.println("Please enter an an amount to transfer");
int amount = scanner.nextInt();
Account receiptient = new Account();
//Credetials cr = new Credetials();
System.out.println("Name of recipient");
String transferName = scanner.next();
receiptient.setClientName(transferName);
System.out.println("id of recipient");
int transferId = scanner.nextInt();
receiptient.setGovId(transferId);
//System.out.println("username");
//String transferNamme = scanner.next();
//cr.setUserName(transferNamme);
//System.out.println("password");
//String tranferPass = scanner.next();
//cr.setPassword(tranferPass);
bank.transfer(username, password, amount, receiptient);
}else if(inpuUserCommand.equalsIgnoreCase("CheckAssets")){
bank.calculateAccountAssets();
}else {
System.out.println("Unknown command");
}
}

======================

//public void deposit(String username, int amount) {
public void deposit(String clientName, int amount) {
for(int index = 0; index < accounts.size(); index++) {
if(amount > 0) {
//if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username)) {
if(accounts.get(index).getClientName().equalsIgnoreCase(clientName)) {
accounts.get(index).deposit(amount);
System.out.println("The new amount is now" + accounts.get(index).getAccountBalance());
}
}else {
System.out.println("Invalid amount!");
}
}
}

public void withdraw(String username, String password, int amount) {
for(int index = 0; index < accounts.size(); index++) {
//if(amount > 0 && accounts.get(index).getAccountBalance() > 0) {
if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username) &&
accounts.get(index).getCredetials().getPassword().equalsIgnoreCase(password)) {
if(amount > 0 && accounts.get(index).getAccountBalance() > 0 && amount < accounts.get(index).getAccountBalance()) {
accounts.get(index).withdraw(amount);
}
//}else {
else if(amount > accounts.get(index).getAccountBalance()){
System.out.println("You don't have enough money in your account");
}

}
}
}

//public void transfer(String username, int amount, Account receipient) {
public void transfer(String username, String password, int amount, Account receipient) {
for(int index = 0; index < accounts.size(); index++) {
//if(amount > 0 && accounts.get(index).getAccountBalance() > 0) {
//if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username)) {
//accounts.get(index).setAccountBalance(accounts.get(index).getAccountBalance() - amount);
//System.out.println("The balance now is" + accounts.get(index).getAccountBalance());
//}
//if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(receipient. getCredetials().getUserName())) {
//accounts.get(index).setAccountBalance(accounts.get(index).getAccountBalance() + amount);
//System.out.println("The balance now is" + accounts.get(index).getAccountBalance());
//}
//}else {
//System.out.println("Invalid amount!");
//}

if(accounts.get(index).getCredetials().getUserName().equalsIgnoreCase(username)
&& accounts.get(index).getCredetials().getPassword().equalsIgnoreCase(password)) {
if(amount < accounts.get(index).getAccountBalance()){
withdraw(username, password, amount);
deposit(receipient.getClientName(), amount);
System.out.println("The balance now is" + accounts.get(index).getAccountBalance());
}else{
System.out.println("Insufficient funds ");
break;
}
}
}
}
0

#6
Потребителят е неактивен   Eyzebio 

  • Група: Потребители
  • Мнения: 49
  • Регистриран: 25-July 09
  • Репутация: 2
Получи се! Работи, ще си я оптимизирам допълнително сега за валидацията на данните :).
0

Споделете тази тема чрез:


Страница 1 от 1
  • Вие не можете да започнете нова тема
  • Вие не може да отговаряте на тази тема

1 потребители четат тази тема
0 регистрирани потребители, 1 гости и 0 анонимни потребители


Data.BG e форум за дискусии. Data.BG не носи отговорност за съдържанието и достоверността на публикуваните в дискусиите материали.

Никаква част от съдържанието на тази страница не може да бъде репродуцирана, записвана или предавана под каквато и да е форма или по какъвто и да е повод без писменото съгласие на Data.BG.

Close  Member Login