How to remove a user from an Array List? - java

package main;
import java.util.ArrayList;
public class UserGroup {
ArrayList<User> userGroup = new ArrayList<>();
User userOne;
public UserGroup() {
addUser(new User("lnb1g16", "Student", "Lee"));
addUser(new User("hpf1g17", "Staff", "Harry"));
addUser(new User("jks1g25", "Student", "Jordon"));
}
public void addUser(User inUser) {
//userGroup.add(new User("LeeB123", "Staff", "Lee"));
userGroup.add(inUser);
}
public ArrayList<User> getUserGroup() {
return userGroup;
}
public void removeFirstUser() {
userGroup.remove(0)
}
}
I've tried creating a method that removes the first user and seems to be compiling but does not actually remove the user when the program is compiled. Any ideas on how to fix this would be great, thanks.
Main method for calling the program
package main;
public class Main{
public static void main(String[] args) {
for (int counter=2; counter<=40; counter+=2) {
System.out.println(counter);
}
System.out.println("For loop complete.");
int counter = 1;
int increment = 2;
int loopexeccounter = 0;
while (counter <= 500) {
loopexeccounter = loopexeccounter + 1;
System.out.println(counter);
counter = counter + increment++;
}
System.out.print("This loop iteratted "+loopexeccounter+" times.\n");
{
//public User callUserGroup;
UserGroup userGroupObject = new UserGroup();
for (User curUser : userGroupObject.getUserGroup()) {
System.out.println(curUser.toString());
}
}
}
}
User method for declaring user's details
package main;
class User {
String username;
String userType;
String name;
User(String username, String userType, String name) {
this.username = username;
this.userType = userType;
this.name = name;
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
#Override
public String toString() {
return username + " " + userType;
}
}

It's working good :
` public static void main(String[] args) {
UserGroup MyUser = new UserGroup();
for (User curUser : MyUser.getUserGroup()) {
System.out.println(curUser.toString());
}
MyUser.removeFirstUser();
System.out.println("your user removed!");
for (User curUser : MyUser.getUserGroup()) {
System.out.println(curUser.toString());
}
}`
RESULT :
`User#4554617c 1
User#74a14482 2
User#1540e19d 3
your user removed!
User#74a14482 1
User#1540e19d 2`

Related

I am getting null as outcome ? Could anyone catch and rectify for the same Thanks

This method I created
public class Use {
private
String firstname;
String lastname;
public String output() {
return "Hii my name is " + firstname + lastname;
}
public String getFirstName() {
return firstname.toUpperCase();
}
public void setFirstName(String jl) {
firstname = jl.strip() ;
}
public String getLastName() {
return lastname.toUpperCase();
}
public void setLastName(String FN) {
lastname = FN.strip();
}
}
And I am trying to use the above method in this code:
import java.util.ArrayList;
import java.util.List;
public class MySweetProgram {
public static void main(String[] args) {
String[] firstnames = {"KARRIK", "KESHAV", "Sussy"};
String[] lastnames = {"gulati", "gulati", "smith"};
List <User> users = new ArrayList<User>();
for (int i = 0; i < firstnames.length; i ++) {
User user = new User();
user.setFirstName(firstnames[i]);
user.setLastName(lastnames[i]);
users.add(user);
}
for (User user : users) {
System.out.println(user.getfullname());
}
}
}
on running getting null null null
1: There is no such class 'Use' in 'MySweetProgram' class (Typo: User)
2: There is no such method in 'Use, class as 'getfullname()'
Solution: Change the class name to User And replace 'getfullname()' with 'output()'.
'
import java.util.ArrayList;
import java.util.List;
public class MySweetProgram {
public static void main(String[] args) {
String[] firstnames = { "KARRIK", "KESHAV", "Sussy" };
String[] lastnames = { "gulati", "gulati", "smith" };
List<User> users = new ArrayList<User>();
for (int i = 0; i < firstnames.length; i++) {
User user = new User();
user.setFirstName(firstnames[i]);
user.setLastName(lastnames[i]);
users.add(user);
}
for (User user : users) {
System.out.println(user.getfullname());
}
}
}
//User Class
class User {
private String firstname;
private String lastname;
public String output() {
return "Hii my name is " + firstname + lastname;
}
public String getfullname() {
return firstname + "_" + lastname;
}
public String getFirstName() {
return firstname.toUpperCase();
}
public void setFirstName(String jl) {
// firstname = jl.strip();// for java 11
firstname = jl;
}
public String getLastName() {
return lastname.toUpperCase();
}
public void setLastName(String FN) {
// lastname = FN.strip();//for java 11
lastname = FN;
}
}

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);
}

The constructor Client(String, String, String, String, String) is undefined

I have an assignment where I am supposed to simulate a management and billing application for a phone company. I created some classes, and one object for each class, but I get this error: "The constructor Client(String, String, String, String, String) is undefined"
Here are the relevant classes:
public class CreateUsers {
public static void main(String[] args) {
Client client = new Client("user1", "user", "user", "Client", "12345678");
Admin admin = new Admin("user2", "user", "user", "Admin");
Seller seller = new Seller("user3", "user", "user", "Seller");
}
}
public class Client extends Users {
String AFM;
public Client(String u, String n, String s, String p, String i){
this.AFM = i;
this.username = u;
this.name = n;
this.surname = s;
this.property= p;
UsersCount++;
}
public void ViewBill()
{
System.out.println("The bill");
}
public void ViewHistory()
{
System.out.println("The history");
}
public void PayBill()
{
System.out.println("Bill payment");
}
public String getAFM() {
return AFM;
}
}
public class Admin extends Users
{
public Admin() {
UsersCount++;
}
public void CreateSeller()
{
System.out.println("Seller was created!");
}
public void DeleteSeller()
{
System.out.println("Seller was deleted!");
}
public void CreateUser()
{
System.out.println("User was created!");
}
public void DeleteUser()
{
System.out.println("User was deleted!");
}
public void CreateNewProgram()
{
System.out.println("A new program was created!");
}
}
public class Seller extends Users
{
int salary;
String shift;
String pt_or_ft;
public void NewCustomer()
{
System.out.println("Customer was created!");
}
public void IssueBill()
{
System.out.println("Bill was issued!");
}
public void ChangeProgram()
{
System.out.println("Program was changed!");
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getShift() {
return shift;
}
public void setShift(String shift) {
this.shift = shift;
}
public String getPt_or_ft() {
return pt_or_ft;
}
public void setPt_or_ft(String pt_or_ft) {
this.pt_or_ft = pt_or_ft;
}
public Seller() {
UsersCount++;
}
}
public class Users
{
String username;
String name;
String surname;
String property;
static int UsersCount = 0;
static void register()
{
System.out.println("User registerd!");
}
static void login()
{
System.out.println("Login succesful!");
}
static void logout()
{
System.out.println("Logout succesful!");
}
public String getUserame()
{
return username;
}
public void setUsername(String newUsername)
{
this.username = newUsername;
}
public String getName()
{
return name;
}
public void setName(String newName)
{
this.name = newName;
}
public String getSurname()
{
return surname;
}
public void setSurname(String newSurname)
{
this.surname = newSurname;
}
public String getProperty()
{
return property;
}
public void setProperty(String newProperty)
{
this.property = newProperty;
}
public Users() {}
}
I am getting these errors in the CreateUsers class, in the lines where I declared the objects "admin" and "seller".
What am I doing wrong? How can I fix this?
instead of having the public static void main(String[] args) {}
you can have like a public fuction with a method that will include all your variables as parameters for example this is how I would have done it.
public class CreateUsers {
public ClientData(String Client, String Admin, String) {
Client client = new Client("user1", "user", "user", "Client", "12345678");
Admin admin = new Admin("user2", "user", "user", "Admin");
Seller seller = new Seller("user3", "user", "user", "Seller");
}
}

Address class being called from Bank Class

I have 2 classes that extend for each other. I have a mutator method that is calling to the class Address.Java to get the city and state from the class. However the Bank.java class is giving me problems. the specific method giving me problems is
public void setBankAddress(String aCity, String aState)(code is below) I dont know if this makes sense
{
}
Bank.Java
public class Bank
{
private String bankName;
private int bankID;
private Address bankAddress;
public Bank()
{
bankName = "?";
bankID = 0;
bankAddress = new Address();
}
public String getBankName()
{
return bankName;
}
public int getBankID()
{
return bankID;
}
public Address getBankAddress()
{
return bankAddress;
}
public void setBankName(String aBankName)
{
bankName = aBankName;
}
public void setBankID(int aBankID)
{
bankID = aBankID;
}
public void setBankAddress(String aCity, String aState)
{
}
public String toString()
{
return "\nBank name:\t\t" + bankName + "\nBank ID:\t\t" + bankID + "\nBank Address:\t\t" + bankAddress + "\n\n";
}
}
Address. Java
public class Address
{
private String city;
private String state;
public Address()
{
city = "?";
state = "?";
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public void setCity(String aCity)
{
city = aCity;
}
public void setState(String aState)
{
state = aState;
}
public String toString()
{
return city + "," + state;
}
}
Do you just not know how to call methods on objects?
public void setBankAddress(String aCity, String aState)
{
bankAddress.setCity(aCity);
bankAddress.setState(aState);
}
bankAddress is already initialized in the constructor so you can safely call these methods.
However, it's usually good practice to do that outside such methods and pass the whole object itself
Address someAddress = new Address();
someAddress.setCity(aCity);
someAddress.setState(aState);
Bank bank = new Bank();
bank.setBankAddress(someAddress);
...
public void setBankAddress(Address aBankAddress) {
bankAddress = aBankAddress;
}

checking login algorithm

i am currently stucked on how to create a login algorithm which will login a user based on 2 HashMap objects namely Students and StaffMembers from a class DataStorage, i do not know after getting the texts input from LoginHandler() what do i do with them to compare it with my DataStorage .
/* Class DataStorage*/
public class DataStorage
{
HashMap<String, Student> students = new HashMap<String, Student>();
HashMap<String, Staff> staffMembers = new HashMap<String, Staff>();
//Default constructor
public DataStorage(){
}
public void addStaffMember(Staff aAcc)
{
staffMembers.put(aAcc.getAccID(),aAcc);
}
public void addStudentMember(Student aAcc)
{
students.put(aAcc.getAccID(),aAcc);
}
public Staff getStaffMember(Staff aAcc)
{
return staffMembers.get(aAcc.getAccID());
}
public Student getStudent(Student aAcc)
{
return students.get(aAcc.getAccID());
}
public Account authUser(String user, String pass)
{
}
}
/* Class Account*/
public class Account {
private String name;
private String department;
private String username;
private String password;
private String accountID;
public Account()
{
}
public Account(String nm,String dep,String user,String pass, String accID)
{
name = nm;
department = dep;
username = user;
password = pass;
accountID = accID;
}
public void setName(String nm)
{
name = nm;
}
public String getName()
{
return name;
}
public void setDep(String d)
{
department = d;
}
public String getDep()
{
return department;
}
public void setUser(String u)
{
username = u;
}
public String getUser()
{
return username;
}
public void setPass(String p)
{
password = p;
}
public String getPass()
{
return password;
}
public void setAccID(String a)
{
accountID = a;
}
public String getAccID()
{
return accountID;
}
}
/* Class Staff extends account*/
public class Staff extends Account {
public Staff(String n, String id, String dep, String user, String pass)
{
super(n, dep, user, pass, id);
}
}
/** Class Student extends Account**/
public class Student extends Account {
private String studentNRIC;
public Student(String n, String nr, String id, String dep, String user, String pass)
{
super(n, dep, user, pass, id);
studentNRIC = nr;
}
public void setStudentNRIC(String nr)
{
studentNRIC = nr;
}
public String getStudentNRIC()
{
return studentNRIC;
}
}
/* class loginHandler which will handle a login button/
class LoginHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String tempUser;
String tempPass;
tempUser = txfUser.getText();
tempPass = txfPass.getText();
}
}
First of all you should change the getters in DataStorage to have String parameters, so that you can look up a student (or staff member) based on her account ID:
public Student getStudent(String aAcc)
{
return students.get(aAcc);
}
You can then lookup the username in actionPerformed, like
Student student = dataStorage.getStudent(tempUser);
if (student != null && student.getPass().equals(tempPass))
{
// login successful
...
} else {
// Login failed - display error message
}
Similarly for staff members.

Categories

Resources