Method not printing ArrayList content correctly - java

I need to print out the content of my ArrayList however it doesn't print out correctly. More specifically it is the getAccountSaldo in CustomerRegister that is not returning the correct value (if I wanna print out for example a different account).
Here is my code:
Class Account
public class Account {
private Customer customer;
private String nbr;
private double saldo;
public void setNbr(String nbr){
this.nbr = nbr;
}
public String getNbr(){
return nbr;
}
public void setSaldo(double saldo){
this.saldo = saldo;
}
public double getSaldo(){
return saldo;
}
public void setCustomer(Customer customer){
this.customer = customer;
}
public Customer getCustomer(){
return customer;
}
public void withdraw(double amount){
saldo -= amount;
}
public void deposit(double amount){
saldo += amount;
}
}
Class Customer
public class Customer {
private String nbr;
private String namn;
private ArrayList<Account> accounts = new ArrayList<Account>();
public void setNbr(String nbr){
this.nbr = nbr;
}
public String getNbr(){
return nbr;
}
public void setNamn(String namn){
this.namn = namn;
}
public String getNamn(){
return namn;
}
public void setAccounts(ArrayList<Account> accounts){
this.accounts = accounts;
}
public ArrayList<Account> getAccounts(){
return accounts;
}
public void add(Account account){
accounts.add(account);
}
public Account find(String nbr){
for(Account a : accounts){
if(nbr == a.getNbr()){
return a;
}
}
return null;
}
}
Class CustomerRegister
public class CustomerRegister {
private ArrayList<Customer> customers = new ArrayList<Customer>();
public void setCustomers(ArrayList<Customer> customers){
this.customers = customers;
}
public ArrayList<Customer> getCustomers(){
return customers;
}
public void add(Customer k){
customers.add(k);
}
public Customer find(String nr){
for (Customer b : customers){
if (nr == b.getNbr()){
return b;
}
}
return null;
}
public ArrayList<Account> printAccounts(String customerNbr){
Customer l = find(customerNbr);
if (l != null){
return l.getAccounts();
}
return null;
}
// CAN'T SOLVE THIS
public Double getAccountSaldo(String customerNbr, String accountNbr) {
double balance = 0;
Customer custNbr = find(customerNbr);
// Shouldn't it be "Account acctNbr = find(accountNbr);" here?
// Problem is I can't access that method in this class...
if(custNbr != null){
for (Account x : printAccounts(customerNbr)) {
if (accountNbr == x.getNbr()) {
balance += x.getSaldo();
}
return balance;
}
}
return null;
}
}
Class demo:
public class Demo {
public static void main(String[] args){
CustomerRegister r1 = new CustomerRegister();
ArrayList<Account> listOfAccounts = new ArrayList<Account>();
ArrayList<Customer> listOfCustomers = new ArrayList<Customer>();
Customer c = new Customer();
c.setNbr("1");
c.setNamn("Adam Schinn");
Account a = new Account();
a.setNbr("Konto 1");
a.setSaldo(2200);
a.setCustomer(c);
Account b = new Account();
b.setNbr("Konto 2");
b.setSaldo(2000);
b.setCustomer(c);
listOfCustomers.add(c);
listOfAccounts.add(a);
listOfAccounts.add(b);
c.setAccounts(listOfAccounts);
r1.add(c);
r1.setCustomers(listOfCustomers);
for(Account temp : r1.printAccounts("1")){
System.out.println(temp.getNbr() + " Balance: " + temp.getSaldo() + "kr ");
}
for(Customer temp : r1.getCustomers()){
System.out.println("Nr: " + temp.getNbr() + " Namn: " + temp.getNamn());
}
// CAN'T SOLVE THIS
// If I write "Konto 2" instead of "Konto 1" it prints "0.0"
System.out.println(r1.getAccountSaldo("1", "Konto 1"));
}
}
Print out
Konto 1 Balance: 2200.0kr
Konto 2 Balance: 2000.0kr
Nr: 1 Namn: Adam Schinn
2200.0

You can't compare strings using == operator, this will not check equality for content instead it check the address of two strings.
Also the return statement was not at correct position.
I have made few changes to your function, have a try with that :
public Double getAccountSaldo(String customerNbr, String accountNbr) {
double balance = 0;
Customer custNbr = find(customerNbr);
// Shouldn't it be "Account acctNbr = find(accountNbr);" here?
// Problem is I can't access that method in this class...
if(custNbr != null){
for (Account x : printAccounts(customerNbr)) {
if (accountNbr.equals(x.getNbr())) {
balance += x.getSaldo();
}
}
}
return balance;
}

Related

How to display list of accounts and prompt the customer to choose which specific account?

I have been stuck on this for more than 3 days now.
In my main class, ATM, in method verifyCustomer(). When signing in, I'm trying to find a way to ask for a customer ID first. Once verified, then the customers accounts will be listed. After that, the customer will then be prompted to choose which account they want to access, and from there they will be prompted to enter the account number and then the password.
I also have a Gold Account class in which only customers above a certain age "65" are allowed the option to open up. I am having trouble figuring out the logic on how to access that in the initialize() method as well.
I have 3 subclasses to the Account superclass which I didn't include due to there already being too much code.
Any tips?
ATM.java
public class ATM {
private InputReader reader;
private String accountNumber;
private String passcode;
private boolean customerVerified;
private String customerID;
private Bank theBank;
private Customer currentCustomer;
public ATM() {
super();
initialize();
run();
}
public static void main(String[] args) {
new ATM();
}
public void run() {
reader = new InputReader();
boolean exit = false;
while (!exit) {
System.out.println("Welcome to Bank");
System.out.println("Choose one of the following options");
System.out.println("1 - Sign In");
System.out.println("2 - Deposit");
System.out.println("3 - Withdraw");
System.out.println("4 - Display Account Info");
System.out.println("5 - Exit");
System.out.println(">");
int choice = reader.getIntInput();
switch (choice) {
case 1:
verifyCustomer();
break;
case 2:
transactDeposit();
break;
case 3:
transactWithdraw();
break;
case 4:
displayAccountInformation();
break;
case 5:
System.out.println("Thank you for banking at Bank");
System.exit(0);
}
}
}
public void initialize() {
Customer tom = new Customer("Tom", "Smith", "123",70,"A001");
Customer jane = new Customer("Jane", "Smith", "789",18,"A002");
Customer bob = new Customer("Bob", "Smith", "456",32,"A003");
Account tomChequing = new ChequingAccount("CH-123", 0.0,2);
Account tomSavings = new SavingsAccount("SA-123", 50.0);
Account tomGold = new GoldAccount("GL-123",50.0,2.0);
Account janeChequing = new ChequingAccount("CH-789",0.0,2);
Account janeSavings = new SavingsAccount("SA-789", 0.0);
Account bobChequings = new ChequingAccount("CH-456",0.0,5);
Account bobSavings = new SavingsAccount("SA-456", 100.0);
tom.addAccount(tomChequing);
tom.addAccount(tomSavings);
tom.addAccount(tomGold);
jane.addAccount(janeChequing);
jane.addAccount(janeSavings);
bob.addAccount(bobChequings);
bob.addAccount(bobSavings);
theBank = new Bank();
theBank.addCustomer(tom);
theBank.addCustomer(jane);
theBank.addCustomer(bob);
if(currentCustomer.getAge() >= 65) {
currentCustomer.
}
}
public void transactDeposit() {
if (customerVerified) {
System.out.println("Enter the amount to deposit: ");
currentCustomer.getAccountList().addToBalance(reader.getDoubleInput());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a transaction.");
verifyCustomer();
}
}
public void transactWithdraw() {
if (customerVerified) {
System.out.println("Enter the amount to withdraw: ");
currentCustomer.getAccount().subtractFromBalance(reader.getDoubleInput());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a transaction.");
verifyCustomer();
}
}
public void displayAccountInformation() {
if (customerVerified) {
System.out.println("Here is your information.");
System.out.println(currentCustomer.toString());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a trasnsaction.");
verifyCustomer();
}
}
public void verifyCustomer() {
System.out.println("Enter your Customer ID");
customerID = reader.getStringInput();
System.out.println("Which account do you want to access?");
System.out.println("Enter Account Number: ");
accountNumber = reader.getStringInput();
System.out.println("Enter your passcode");
passcode = reader.getStringInput();
currentCustomer = Bank.theBank.get(accountNumber);
if (currentCustomer != null) {
if (passcode.equals(currentCustomer.getPasscode()) && customerID.equals(currentCustomer.getCustomerID())) {
customerVerified = true;
} else {
System.out.println("ERROR: Either account number, customer id, or passcode is not correct.");
run();
}
} else {
System.out.println("ERROR: Either account number, customer id, or passcode is not correct.");
run();
}
}
}
Customer.java
import java.util.ArrayList;
public class Customer {
private String firstName;
private String lastName;
private String passcode;
private int age;
private String customerID;
private ArrayList<Account> accounts;
public Customer(String firstName, String lastName, String passcode, int age, String customerID) {
setFirstName(firstName);
setLastName(lastName);
setPasscode(passcode);
setAge(age);
setCustomerID(customerID);
accounts = new ArrayList<>();
}
public void addAccount(Account account) {
accounts.add(account);
}
public ArrayList<Account> getAccountList() {
return accounts;
}
public void setAccountList(ArrayList<Account> account) {
this.accounts = account;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
if (firstName != null && !firstName.trim().isEmpty()) {
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
if (lastName != null && !lastName.trim().isEmpty()) {
this.lastName = lastName;
}
}
public String getPasscode() {
return passcode;
}
public void setPasscode(String passcode) {
if (passcode != null && !passcode.trim().isEmpty()) {
this.passcode = passcode;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCustomerID() {
return customerID;
}
public void setCustomerID(String customerID){
this.customerID = customerID;
}
}
Account.java
import java.util.ArrayList;
public class Account {
private String accountNumber;
private double balance;
private boolean active;
protected ArrayList<String> transactionInfo;
public Account() {
super();
}
public Account(String accountNumber, double balance) {
super();
if(accountNumber != null) {
this.accountNumber = accountNumber;
}
setBalance(balance);
active = true;
transactionInfo = new ArrayList<String>();
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public boolean isActive() {
return active;
}
public void setBalance(double balance) {
if(balance >= 0){
this.balance = balance;
}
}
public void setActive(boolean active) {
this.active = active;
}
public void addToBalance(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void subtractFromBalance(double amount) {
if (amount > 0) {
balance -= amount;
}
}
public void addTransactionInfo(String info) {
if(info != null) {
transactionInfo.add(info);
}
}
public void displayAccountRecords() {
if(transactionInfo != null) {
for(String info: transactionInfo) {
System.out.println(info);
}
}
}
}
Bank.java
import java.util.HashMap;
public class Bank {
public static HashMap<String, Customer> theBank;
public Bank() {
super();
theBank = new HashMap<>();
}
public void addCustomer(Customer newCustomer) {
if (newCustomer != null) {
theBank.put(newCustomer.getCustomerID(), newCustomer);
}
}
// use the customerID to access their collection of accounts
public void closeAccount(String customerID, String accountNumber) {
Customer c = theBank.get(customerID);
if(c != null) {
for(Account a: c.getAccountList()) {
if(accountNumber.equals(a.getAccountNumber())) {
theBank.remove(accountNumber);
}
}
//if (theBank.containsKey(customerID)) {
//theBank.get(customerID).getAccountList().remove(accountNumber);
}
}
public static void displayCustomerInformation(Customer customer){
if(customer != null){
System.out.println(customer);
}
}
public static void displayAllCustomers(){
for(Customer customer : theBank.values()){
System.out.println(customer);
}
}
}
You have a HashMap in class Bank and the map key is customer ID. Just add a getCustomer(String) method in class Bank.
public Customer getCustomer(String id) {
return theBank.get(id);
}

Having problem with the Output of the Bank Account Program in JAVA

This is my interface class
interface InfBankAccount
{
void deposit(double amt);
boolean withdraw(double amt);
String toString();
}
This is my abstract class
abstract class AbsBankAccount
{
private static long id;
protected String name;
protected long AccNo;
protected double currBalance;
public void deposit(double amt)
{
currBalance += amt;
}
protected void AssignAccNo()
{
AccNo = ++id;
}
public abstract boolean withdraw(double amt);
public static long getLastAccNo()
{
return id;
}
public String toString()
{
String str = " ";
str = str + "\nName of Account Holder : " +name;
str = str + "\nAccount Number : " +AccNo;
str = str + "\nCurrent Balance : Rs." +currBalance;
return str;
}
static
{
id = 100;
}
}
This is my Saving Account Class
class SavingBankAccount extends AbsBankAccount
{
protected double minBalance;
SavingBankAccount(String name, double currBalance, double minBalance)
{
this.name = name;
this.currBalance = currBalance;
this.minBalance = minBalance;
AssignAccNo();
}
public String toString()
{
String str = super.toString();
str = str + "\nMinimum Balance : Rs." + minBalance;
return str;
}
public boolean withdraw(double amt)
{
boolean flag = true;
if(currBalance - amt < minBalance)
{
flag = false;
}
else
{
currBalance -= amt;
}
return flag;
}
public static long getLastAccNo()
{
return AbsBankAccount.getLastAccNo();
}
}
This is my Current Bank Account
class CurrentBankAccount extends AbsBankAccount
{
protected double overDraftLimit;
CurrentBankAccount(String name, double currBalance, double odl)
{
this.name = name;
this.currBalance = currBalance;
overDraftLimit = odl;
AssignAccNo();
}
public String toString()
{
String str = super.toString();
str = str + "\nOverdraft Limit : Rs." +overDraftLimit;
return str;
}
public boolean withdraw(double amt)
{
boolean flag = true;
if( overDraftLimit + currBalance < amt)
{
flag = false;
}
else
{
currBalance -= amt;
}
return flag;
}
public static long getLastAccNo()
{
return AbsBankAccount.getLastAccNo();
}
}
This is my Main Class
class InheritanceDemo
{
public static void main(String[] args)
{
AbsBankAccount abs;
abs = new SavingBankAccount("Issac Newton", 12000, 1000);
System.out.println(abs);
if(abs.withdraw(100))
{
System.out.println("\nWithdrawl Successful");
System.out.println(abs);
}
else
{
System.out.println("\nWithdrawl Unsuccessful");
System.out.println(abs);
}
InfBankAccount inf;
inf = new CurrentBankAccount("Leonard Euler", 2000, 1000);
System.out.println(inf);
if(inf.withdraw(12000))
{
System.out.println("\nWithdrawl Successful");
System.out.println(inf);
}
else
{
System.out.println("\nWithdrawl Unsuccessful");
System.out.println(inf);
}
inf.deposit(55000);
System.out.print(inf);
}
}
Output must contain the data of both Saving account as well as current account, but the main class giving me the following error
incompatible types: CurrentBankAccount cannot be converted to InfBankAccount
When I just use the saving account only in my main class, it's working fine with the proper output. I need the data of both saving account and current account.

Login to a specific customer using a file-objectinputstream

My program is meant to be a banking application. When you start it you can either create a customer or login in as an existing user. For now i can only use customers which i create during the time i run my program but want my program to save the customers even after the program has been closed.
My problem: after creating a customer i close the program-> restart it and try to log in but i get an error: "java.lang.ClassCastException: java.lang.String cannot be cast to nictho7.Customer
at nictho7.GUI$AL.actionPerformed(GUI.java:221)" this row is mine "nictho7.Customer a = (nictho7.Customer) infil.readObject();" below.
"Customer" is a class for my custmers has name,surname & ID.
"bang" is short for my logic class where i store this file.
I reason that the program read from my file searching for object that resembles Customer saves them to the variable "a" and if that variable has an ID which equals the text a user enters it should be fine? But obviously there is something that I'm missing, or maybe sevral things...
**update 12-30
I want to add my customers to a list - customers contains:name,surname,ID & array of diffrent accounts(cred/savings).
when i create and run this "new" code(compared to my original post) i get an IOException but I can now access the customer account through the list i created, how can i get rid of that IOException?
2.After adding a creditaccount to my customer i close the program and restart it, when i try to login i recieve this message: >
java.lang.ClassCastException: java.lang.Boolean cannot be cast to nictho7.Customer
at nictho7.GUI$AL.actionPerformed(GUI.java:224)<
I understand what Java is telling me, >a boolean can not be cast to a customer cuz my customer does not contain any boolean< but I fail to see where i am trying to do so and how I could fix this?
Line 224 is my refering to the code in my try{ while(true)-loop: a = (Customer) infil.readObject();`
if (ClickedButton == kund) {
// JTextField username = new JTextField();
JTextField ID = new JTextField();
// med ok-och avbrytknapp inbyggd
Object[] message = { "Personal identity number:", ID, };
int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
Customer = ID.getText();
// if ((bang.searchCustomer(ID.getText()) != null)) {
// System.out.println("Login successful");
//
// JFrame frame = new customer();
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setTitle("Bank");
// frame.setVisible(true);
// }
if (bang.data.exists()) {
ObjectInputStream infil = null;
try {
infil = new ObjectInputStream(new FileInputStream("C:\\Users\\nickt\\eclipse-workspace\\nictho7\\Bankdata.dat"));
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "IOEfil");
e1.printStackTrace();
} catch (ClassCastException e1) {
JOptionPane.showMessageDialog(null, "classcast111111");
e1.printStackTrace();
}
try {
while (true) {
Customer a = new Customer();
a = (Customer) infil.readObject();
bang.customers.add( a );
if (infil != null) {
infil.close();
}
}
} catch (ClassNotFoundException e1) {
JOptionPane.showMessageDialog(null, "File not found");
e1.printStackTrace();
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "IOEinlasning");
e1.printStackTrace();
} catch (ClassCastException e1) {
JOptionPane.showMessageDialog(null, "classcast");
e1.printStackTrace();
}finally {
// Close the ObjectInputStream
try {
if (infil != null) {
infil.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
if ((bang.searchCustomer(ID.getText()) != null)) {//(a.getPersonalNumber() == ID.getText()) {
System.out.println("Login successful");
JFrame frame = new customer();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Bank");
frame.setVisible(true);
}
}
}
Customer
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Customer implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int Arraylist = 0;
// ------- Instansvariabler ----------
private String name;
private String surname;
private String personalNumber;
public Customer() {
super();
accounts = new ArrayList<>(); // credit och saving finns med i denna lista.
}
// ------- lista med konton ----------
public ArrayList<Account> accounts;
// ------- Konstruktör ----------
public Customer(String cName, String surName, String pNumber, ArrayList<Account> a) {
name = cName;
surname = surName;
personalNumber = pNumber;
accounts = a;
}
// ------- Get- & set-metoder ----------
public String getCustomer() {
return name + " " + surname + " " + personalNumber;
}
public String getCustomerSurname() {
return surname;
}
public void setCustomerSurname(String customerSurname) {
surname = customerSurname;
}
public String getcustomerName() {
return name;
}
public void setcustomerName(String customerName) {
name = customerName;
}
public String getPersonalNumber() {
return personalNumber;
}
public void setPersonalNumber(String PersonalNumber) {
personalNumber = PersonalNumber;
}
public ArrayList<Account> getAccountList() {
return accounts;
}
// void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException
// {
// name = (String) in.readObject();
// surname = (String) in.readObject();
// personalNumber = (String) in.readObject();
// }
private void readObject(
ObjectInputStream in
) throws ClassNotFoundException, IOException {
//always perform the default de-serialization first
in.defaultReadObject();
name = getcustomerName();
//ensure that object state has not been corrupted or tampered with maliciously
// validateState();
}
}
Account
import java.util.Random;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
public abstract class Account implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
// ------- Instansvariabler ----------
private double interestRate;
private double balance;
private int accountNumber;
private static int lastassignedNumber = 1001;
private double debtRate = 7;
private String accType;
private double credLimit;
// lista för transaktioner och variabel för tid.
protected ArrayList<String> transactionsList = new ArrayList<String>();
// random datum för transaclist
Random rnd = new Random();
// Date date = new Date(Math.abs(System.currentTimeMillis() - rnd.nextInt()));
// default konto
public Account() {
setAccountNumber(getlastassignedNumber());
}
// Presentationsmetoder
public double Withdraw(Account a, double amount) {
a.setBalance(a.getBalance() - amount);
return getBalance();
}
public double Deposit(Account a, double amount) {
a.setBalance(a.getBalance() + amount);
return a.getBalance();
}
public static int getLastassignedNumber() {
return lastassignedNumber;
}
public void setAccountNumber(int d) {
this.accountNumber = d;
}
public double TransactionToAnotherAcc(Account Acc1, Account Acc2, double amount) {
if (Acc1.getBalance() > amount) {
Acc2.setBalance(Acc2.getBalance() + amount);
Acc1.setBalance(Acc1.getBalance() - amount);
double a = Acc1.getBalance();
return a;
}
else
System.out.print("Your requested amount cannot be transactioned due to insufficient funds");
return 0;
}
protected abstract String getspecinfo();
public String getinfo() {
return getcommoninfo() + getspecinfo();
}
public String getcommoninfo() {
String info = accountNumber + " " + getBalance();
return info;
}
// ------- Get-metoder ----------
public double getRate(double balance) {
double interestrate = balance / interestRate;
return interestrate;
}
public void getbalance(int balance) {
this.balance = balance;
}
public int getAccountNumber() {
return accountNumber;
}
public int getlastassignedNumber() {
accountNumber = lastassignedNumber;
++lastassignedNumber;
return accountNumber;
}
public String getAccount() {
return accountNumber + " " + getBalance();
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getInterestRate() {
return interestRate;
}
public void setInterestRate(double interestRate) {
this.interestRate = interestRate;
}
public ArrayList<String> getTransactionsList() {
return transactionsList;
}
public String inreturnintrest(double d) {
if (d < 0) {
d = (d * 7) / 100;
String info1 = debtRate + " " + d;
return info1;
}
else
d = (d * (0.5 / 100));
String info2 = interestRate + " " + d;
return info2;
}
public String getAccType() {
return accType;
}
public void setAccType(String accType) {
this.accType = accType;
}
public double getCredLimit() {
return credLimit;
}
public void setCredLimit(double credLimit) {
this.credLimit = credLimit;
}
// private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException
// {
// interestRate = (double) in.readObject();
// balance = (double) in.readObject();
// accountNumber = (int) in.readObject();
// lastassignedNumber = ( int ) in.readInt();
// debtRate = (double) in.readObject();
// accType = (String) in.readObject();
// credLimit = (double) in.readObject();
//
// }
private void readObject(
ObjectInputStream in
) throws ClassNotFoundException, IOException {
//always perform the default de-serialization first
in.defaultReadObject();
//make defensive copy of the mutable Date field
// fDateOpened = new Date(fDateOpened.getTime());
//ensure that object state has not been corrupted or tampered with maliciously
// validateState();
}
}
Functions in my Logic-class to call the functions im trying to fix
public int createSavingsAccount(String pNr) {
for (int i = 0; i < customers.size(); i++) {
if ((customers.get(i).getPersonalNumber()).equals(pNr)) {
SavingAccount newaccount = new SavingAccount();
customers.get(i).accounts.add(newaccount); // saccounts
return newaccount.getAccountNumber();
}
}
return -1;
}
public boolean createCustomer(String name, String surename, String pNr, ArrayList<Account> b) throws FileNotFoundException, IOException {
boolean createCustomer = true;
b = new ArrayList<>();
#SuppressWarnings({ })
ObjectOutputStream utfil = new ObjectOutputStream (new FileOutputStream(data));
for (int i = 0; i < customers.size(); i++) {
if ((customers.get(i).getPersonalNumber()).equals(pNr)) {
createCustomer = false;
}
}
if (createCustomer != false) {
customers.add(new Customer(name, surename, pNr, b));
//sparar kunden som objekt för loggin
Customer a = new Customer (name, surename, pNr,b);
createCustomer = true;
//name = (String)
utfil.writeObject(a);
//surename = (String)
// utfil.writeObject(surename);
//pNr = (String)
// utfil.writeObject(pNr);
// utfil.writeObject(b);
utfil.writeObject(a);
utfil.close();
}
return createCustomer;
}

Circular Queue in Java

I am implemeting a circular queue in java which will accept objects (Employee) as entries. Now I have a method to edit the surname of the specific object, but somehow I cannot access the surname setter method found in the Employee class from the CQueue class even though I am importing all the required packages. Here is the code:
//PACKAGES IMPORTED
package linearstructures;
import dataobjects.*;
import linearnodes.*;
public class CQueue{
Node front, rear, temp;
boolean full = false;
String key;
public AnyClass searchKey(String key)
{
temp = rear.next; // first node
do
{
if (temp.obj.getKey().equals(key))
return temp.obj;
temp = temp.next;
} while (temp != rear.next);
return null;
}
public AnyClass editObject(String key){
int choice, newSeqNo;
double newPay;
boolean exit = false;
Employee etemp = new Employee(); //INCLUDED THIS AFTER EDIT
searchKey(key);
if(searchKey(key) != null){
temp.obj.getData();
System.out.println();
System.out.println("------------------------");
System.out.print("Enter new Salary: ");
newPay = sc.nextDouble();
System.out.println("------------------------");
System.out.println();
etemp.setPay(newPay); //INCLUDED THIS AFTER EDIT
else
System.out.println("NO OBJECT WAS FOUND!");
return null;
}
}
Employee class:
package dataobjects;
public class Employee extends AnyClass
{
public String surname;
public double pay;
public Employee(){}
public Employee(int seqNo, String surname, double pay)
{
super(seqNo);
this.surname = surname;
this.pay = pay;
}
public double getSalary()
{
return pay;
}
public void setPay(double newPay)
{
pay = newPay;
}
public String getData()
{
return super.getData() + ", Surname: " + surname + ", Pay: " + pay;
}
public String getKey()
{
return surname;
}
}
AnyClass class:
package dataobjects;
public class AnyClass
{
public int seqNo;
public AnyClass(){}
public AnyClass(int seqNo)
{
this.seqNo = seqNo;
}
public int getseqNo()
{
return seqNo;
}
public void setseqNo(int seqNo) {
this.seqNo = seqNo;
}
public String getData()
{
return "Sequential Number - " + seqNo;
}
public String getKey()
{
return Integer.toString(seqNo);
}
public void edit(){}
}
Node Class
package linearnodes;
import dataobjects.*;
public class Node{
public AnyClass obj;
public Node next;
public Node(AnyClass obj){
next = null;
this.obj = obj;
}
}
Your editobject method could be something like this:
public AnyClass editObject(String key){
// ...
// Store your search result to avoid performing searchKey twice
AnyClass searchResult = searchKey(key);
if( searchResult != null ){
// Check if searchResult is an Employee object
if( searchResult instanceof Employee )
// Cast AnyClass to Employee
Employee empl = (Employee) searchResult;
// Your logic here...
// Set properties of the Employee object
empl.setPay(newPay);
// ...
return empl;
}
// Add 'else if' here, if you need to manage other Object types
// otherwise you can join previous if conditions
}
else
System.out.println("NO OBJECT WAS FOUND!");
return null;
}
Your code creates a new local Employee instance that dies when the method ends, its value will be lost because no object points to it.
for include pay "etemp.setPay(newPay);" you will change return object to Employee.
public Employee editObject(String key){
Employee etemp = new Employee(); //INCLUDED THIS AFTER EDIT
....
....
etemp.setPay(newPay); //INCLUDED THIS AFTER EDIT
return etemp;
}
because AnyClass hasn't "public double pay;"

Print out customer name, id, balance

I am writing a Java program that I need:
A method to read the customer names and id and store them in an array. (Read a sequence of zero or more lines each containing the name and id of one customer. Instantiate one Customer object per line and store each object in an array of objects. The array need not be more than 10 elements long. The sequence of name and id will end with an empty line).
Main
import java.util.Scanner;
public class CustomerTest {
public static void main(String[] args) {
Customer[] customers = new Customer[10];
Scanner myScanner = new Scanner(System.in);
int numItem;
readCustomer(myScanner, customers); //not sure about this calling
readNameAmount(myScanner, customers); ////not sure about this calling
}
public static void readCustomer(Scanner myScanner, Customer[] input) {
boolean streamEnded = false;
int numItem = 0;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
} else {
input[numItem] = name; //error
input[numItem] = id; //error
}
numItem++;
Customer customerTest = new Customer(name, id);
}
}
public static void readNameAmount(Scanner myScanner, Customer[] input) {
while (myScanner.hasNext()) {
String id = myScanner.nextLine();
double amount = myScanner.nextDouble();
int i = 0;
boolean found = false;
while (i <numItem && !found) { //error
if (customers[i].equals(id)) { //error
changeBalance(double value);//error
}
found = true;
i++;
}
}
}
public static void print(Customer[] input, int numItem) {
for (int i = 0; i < numItem; i++) {
System.out.println(customers[i].toString()); //error
}
}
}
Can you please check if this works.
I dont know whether I understood your question.And I just cleared the error.
public class CustomerTest {
static int numItem = 0;
public static void main(String[] args) {
Customer[] customers = new Customer[10];
Scanner myScanner = new Scanner(System.in);
readCustomer(myScanner, customers); //not sure about this calling
readNameAmount(myScanner, customers); ////not sure about this calling
}
public static void readCustomer(Scanner myScanner, Customer[] input) {
boolean streamEnded = false;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
}
else {
input[numItem].getName();
input[numItem].getId(); //error
}
numItem++;
Customer customerTest = new Customer(name, id);
}
}
public static void readNameAmount(Scanner myScanner, Customer[] input) {
while (myScanner.hasNext()) {
String id = myScanner.nextLine();
Customer cust = new Customer();
double amount = myScanner.nextDouble();
int i = 0;
boolean found = false;
while (i < numItem && !found) { //error
if (input[i].equals(id)) { //error
cust.changeBalance(amount);//error
}
found = true;
i++;
}
}
}
public static void print(Customer[] input, int numItem) {
for (int i = 0; i < numItem; i++) {
System.out.println(input[i].toString()); //error
}
}
}
Let me know your thoughts.
Customer.java
public class Customer {
private String name;
private String id;
private double balance;
public Customer(){
}
public Customer(String name, String id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public void changeBalance(double value) {
balance = balance + value;
}
public String toString() {
return "name " + name + " id " + id + " balance " + balance;
}
}

Categories

Resources