Out of bounds exception for my quicksort method - java

When i pass the value to my quick sort method it intialls sets the pivot to the list size but after going through the loop every value gets reset to zero and throws an out of bounds exception.
This is the method in question
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
This is the rest of the program
import java.io.IOException;
import java.util.*;
import java.util.HashMap;
import java.time.LocalDate;
public class BankingSystem {
private int option = 0;
int key;
Double newAccBalance;
String transType;
Double transAmount;
ArrayList<Transaction> list = new ArrayList<>();
HashMap<Integer, Account> accounts = new HashMap<>();
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws IOException, InputMismatchException{
BankingSystem bankingSystem = new BankingSystem();
bankingSystem.mainLoop();
}
public void mainLoop() {
option = 0;
while (option != 6) {
display();
option = getKeyboardInteger(keyboard);
if (option == 1) {
createAccount();
} else if (option == 2) {
showAccounts();
} else if (option == 3) {
transaction();
} else if (option == 4) {
deleteAccount();
} else if (option == 5) {
showTransactions();
}
}
}
void display(){
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Main Menu-------------------------------|
---------------------------------------------------------------|
Please select option |
1. Create Account |
2. Display Accounts |
3. Deposit/Withdraw |
4. Delete Account |
5. View Transactions |
6. Exit Program |
---------------------------------------------------------------|
>""");
}
public void createAccount() {
System.out.print("""
---------------------------------------------------------------|
------------------------Create Account Menu--------------------|
---------------------------------------------------------------|
1. Create Account |
2. Return to Main Menu |
""");
while (option == 1 && option !=2) {
System.out.print("Please enter the new account number > ");
int accNum = getKeyboardInteger(keyboard);
System.out.print("Please enter the name of the account holder > ");
String accName = getKeyboardString(keyboard);
System.out.print("Please enter the address of the account holder>> ");
String accAdd = getKeyboardString(keyboard);
System.out.print("Please enter the starting balance: ");
Double accOpBalance = getKeyboardDouble(keyboard);
LocalDate accOpDate = LocalDate.now();
System.out.print("Account open date: " + accOpDate);
Account newAccount = new Account(accNum, accName, accAdd, accOpDate, accOpBalance);
accounts.put(accNum, newAccount);
System.out.print("*Account " + accNum + " added to database* "+ "\n" + ">");
option = getKeyboardInteger(keyboard);
}
}
public void showAccounts() {
option = 0;
while (option == 1 || option != 2){
System.out.print("""
---------------------------------------------------------------|
-----------------------Show Account Menu-----------------------|
---------------------------------------------------------------|
1. View all Accounts |
2. Return to Main Menu |
>""");
option = getKeyboardInteger(keyboard);
for (Map.Entry<Integer, Account> accountEntry : accounts.entrySet()) {
System.out.println("Account key(number) = " + accountEntry.getKey() + accountEntry.getValue());
System.out.println("---------------------------------------------------------------|");
}
}
}
public void deleteAccount(){
int key;
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Delete Menu-----------------------------|
---------------------------------------------------------------|
1. Delete Account |
2. Main Menu |
>""");
while(option != -1) {
System.out.print("""
Select Account Number
>""");
key = getKeyboardInteger(keyboard);
accounts.remove(key);
option = getKeyboardInteger(keyboard);
}
}
public void transaction(){
option = 0;
while(option != 3){
System.out.println("""
---------------------------------------------------------------|
-----------------------Transaction Menu------------------------|
---------------------------------------------------------------|
Please select the type of transaction:
1. Deposit
2. Withdraw
3. Main Menu""");
option = getKeyboardInteger(keyboard);
switch(option){
case 1 -> {
doDeposit();
break;
}
case 2 -> {
doWithdrawal();
break;
}
}
}
}
public void doWithdrawal(){
transType = "Withdrawal";
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
System.out.print("How Much would you like to withdraw > ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount > getBalance) {
System.out.println("Insufficient funds");
}else{
newAccBalance = getBalance - transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void doDeposit(){
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
transType = "Deposit";
System.out.print("How Much would you like to deposit? ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount <= 0) {
System.out.print("Please enter a positive value!");
}else {
newAccBalance = getBalance + transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void showTransactions() {
option = 0;
key = getKeyboardInteger(keyboard);
list = accounts.get(key).transList;
myQuickSort(list);
while(option != 2) {
System.out.print("""
---------------------------------------------------------------|
-------------------Show Transactions Menu----------------------|
---------------------------------------------------------------|
1.View Transactions
2.Main Menu
>""");
for(int i = 0; i < accounts.get(key).transList.size(); i++){
System.out.print(accounts.get(key).transList.get(i));
}
option = getKeyboardInteger(keyboard);
}
}
public String getKeyboardString(Scanner keyboard){
while (true){
try{
return keyboard.next();
}catch(Exception e){
keyboard.next();
System.out.print("Something went wrong! Please try again" + "\n> ");
}
}
}
public int getKeyboardInteger(Scanner keyboard){
while(true){
try{
return keyboard.nextInt();
}catch(Exception e){
keyboard.next();
System.out.print("Not an option! Please enter a valid option" + "\n> ");
}
}
}
public Double getKeyboardDouble(Scanner Double){
while(true){
try{
return keyboard.nextDouble();
}catch (Exception e){
keyboard.next();
System.out.print("Not an option! Enter an Integer or Decimal value" + "\n>");
}
}
}
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
}
import java.time.LocalDate;
import java.util.ArrayList;
public class Account{
private int accNum;
private String accName;
private String accAdd;
private LocalDate accOpDate;
private Double accOpBalance;
public ArrayList<Transaction> transList;
public Account(int accNum, String accName, String accAdd, LocalDate accOpDate, Double accOpBalance){
setAccNum(accNum);
setAccName(accName);
setAccAdd(accAdd);
setAccOpDate(accOpDate);
setAccOpBalance(accOpBalance);
transList = new ArrayList<Transaction>();
}
public void setAccNum(int accNum){
this.accNum = accNum;
}
public int getAccNum(){
return accNum;
}
public void setAccName(String accName){
this.accName = accName;
}
public void setAccAdd(String accAdd){
this.accAdd = accAdd;
}
public void setAccOpDate(LocalDate accOpDate){
this.accOpDate = accOpDate;
}
public void setAccOpBalance(Double accOpBalance){
this.accOpBalance = accOpBalance;
}
public Double getAccOpBalance(){
return accOpBalance;
}
#Override
public String toString() {
return "\n" + "Account Number: " + accNum + "\n" + "Name: " + accName +
"\n" + "Account Holder Address: " + accAdd + "\n" +"Account open date: "
+ accOpDate + "\n" + "Account balance: " + accOpBalance;
}
}
import java.util.ArrayList;
public class Transaction extends ArrayList implements Comparable<Transaction> {
private Double transAmount;
private String transType;
public Transaction(Double transAmount, String transType){
this.transAmount = transAmount;
this.transType = transType;
}
public void setTransAmount(Double transAmount){
this.transAmount = transAmount;
}
public String getTransType(){
return transType;
}
public void setTransType(String transType){
this.transType = transType;
}
public Double getTransAmount(){
return transAmount;
}
#Override
public int compareTo(Transaction compareAcc){
if(this.transAmount < compareAcc.transAmount)
return -1;
else if (compareAcc.transAmount < this.transAmount)
return 1;
return 0;
}
#Override
public String toString() {
return "\n" + "Transaction type: " + transType +
"\n" + "Amount: " + transAmount + "\n";
}
}
Ive tried running through the code step by step in intellij but cant quite figure it out.

Well, I'd like to make this quick and easy to understand. The problem here is that it recurses infinitely. Everytime it reaches the
lesser = myQuickSort(lesser);
line is recurses. And keep in mind that the list parameter this method receives shrinks in size every time it recurses. Because, for example, the first time you give it a list of size 100 then it gets sorted into lesser/greater and then lesser invokes the method again and it recurses again but this time the arraylist given as the parameter is less than the first. Until it reaches a point where the list has pivot = 0 in it and when it's done sorting that it recurses for one final time and attempts to run this line of code.
Transaction pivot = list.get(list.size()-1);
Which attempts to get the Transaction at the -1 index since the list at this point is empty so the size = 0. This causes an ArrayIndexOutOfBoundsException.
This is a very problematic method and also keep in mind that you probably need a base case to stop it from recurring infinitely and also a few improvements in general.
Hope this helps.
Edit: also due to the infinite recursion this method could cause a stackoverflow error

Related

Is it possible to create a text file and then on the same run or runtime of the code also read and write in these files? Java

I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.
The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.
Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?
import java.util.Scanner;
import java.io.*;
public class FileManagement {
static String pathnameFile = "src\\Log";
static File directory = new File(pathnameFile);
static String[] allFiles = directory.list();
public static void createFolder() {
File logFile = new File(pathnameFile);
if (!logFile.exists()) {
logFile.mkdir();
}
}
public static void writeFiles() throws IOException {
FileWriter writer;
for (int i = 0; i < allFiles.length; i++) {
writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
writer.close();
}
}
//original method
/*public static void readFiles() {
Scanner reader;
for (int i = 0; i < allFiles.length; i++) {
reader = new Scanner(pathnameFile + allFiles[i]);
}
}*/
//My solution
public static void readFiles() throws IOException{
if(directory.exists() == false || allFiles == null) {
return;
}
Scanner reader;
File currentFile;
String[] data = new String[4];
for(int i = 0; i < allFiles.length; i++) {
currentFile = new File(pathnameFile + "\\" +allFiles[i]);
reader = new Scanner(currentFile);
int count = 0;
while(reader.hasNextLine()) {
if(!reader.hasNext()) {
break;
}
reader.next();
data[count] = reader.next();
count++;
}
reader.close();
String accountName = data[0];
String PIN = data[1];
int balance = Integer.parseInt(data[2]);
eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
}
}
}
import java.util.Scanner;
import java.io.*;
public class App {
public static eBanking currentAccount;
public static void mainMenu() throws Exception{
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("""
--------------------------------------------------------
1. Log in
2. Register
0. Exit.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
System.out.println("Please enter your account name and PIN below.");
System.out.print("Account name: ");
String accountName = input.next();
System.out.print("PIN: ");
String PIN = input.next();
System.out.println();
for (int i = 0; i < eBanking.accounts.length; i++) {
if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
eBanking.accounts[i].welcome();
currentAccount = eBanking.accounts[i];
break;
}
}
menu();
}
case 2 -> {
System.out.println("Please enter the account name, PIN and inital balance of your new account.");
System.out.print("Account name:");
String accountNameRegister = input.next();
System.out.print("PIN: ");
String registerPIN = input.next();
System.out.print("Initial balance: ");
int initialBalance = input.nextInt();
currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
menu();
}
default -> {
FileManagement.writeFiles();
System.exit(0);
}
}
}
}
public static void menu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("""
--------------------------------------------------------
1. Show your balance.
2. Withdraw money.
3. Deposit money.
4. Change your PIN.
5. Transfer money to another person.
0. Back.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
currentAccount.showBalance();
}
case 2 -> {
System.out.println("Please enter the amount you want to withdraw: ");
int withdrawAmount = input.nextInt();
currentAccount.withdraw(withdrawAmount);
}
case 3 -> {
System.out.println("Please enter the amount you want to deposit: ");
int depositAmount = input.nextInt();
currentAccount.deposit(depositAmount);
}
case 4 -> {
currentAccount.changePIN();
}
case 5 -> {
System.out.println("Please enter the amount you want to send: ");
int amount = input.nextInt();
System.out.println("Please enter the account number you want to send the money to: ");
String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)
System.out.println("The amount of money is completed");
currentAccount.transfer(amount, transferAccount);
}
case 0 -> {
return;
}
default -> {
System.out.println("Please enter a number from the menu list!");
}
}
}
}
public static void main(String[] args) throws Exception {
FileManagement.createFolder();
FileManagement.readFiles();
mainMenu();
}
}
import java.util.Scanner;
import java.io.*;
public class eBanking extends BankAccount {
// Variable declaration
Scanner input = new Scanner(System.in);
private String accountName;
private String accountID;
public static eBanking[] accounts = new eBanking[100];
// Methods
public String getAccountName() {
return accountName;
}
public void welcome() {
System.out.println("---------------------------------------------------------------------------------------");
System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
}
public void transfer(int x, String str) {
boolean foundID = false;
withdraw(x);
if (initialBalance == 0) {
System.out.println("Transaction failed!");
} else if (initialBalance < x) {
for(int i = 0; i < numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += initialBalance;
System.out.println("Transaction completed!");
foundID = true;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += initialBalance;
return;
}
} else {
for(int i = 0; i <= numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += x;
System.out.println("Transaction completed!");
foundID=true;
return;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += x;
return;
}
}
}
// Constructors
public eBanking(String name){
int firstDigit = (int)(Math.random() * 10);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);
int forthDigit = (int)(Math.random() * 10);
accountID = this.toString();
PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha
balance = 0; //dhe nuk duhet ta perseris per the gjitha
accountName = name;
accounts[numberOfAccount] = this;
numberOfAccount++;
System.out.println("---------------------------------------------------------------------------------------");
System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
}
public eBanking(String name, String pin, int x){
if (checkPIN(pin) == false) {
System.out.println("Incorrect PIN format!");
return;
}
accountID = this.toString();
accountName = name;
balance = x;
PIN = pin;
accounts[numberOfAccount] = this;
numberOfAccount++;
welcome();
}
}
import java.util.Scanner;
public abstract class BankAccount {
// Variable declaration
protected String PIN;
protected int balance;
public static int numberOfAccount = 0;
protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();
//Methods
//Balance
public int getBalance() {
return balance;
}
public void showBalance() {
System.out.println("The total balance of the account is " + balance);
}
public void withdraw(int x) {
initialBalance = balance;
if (balance == 0) {
System.out.println("The deduction has failed due to lack of balance!");
return;
}
if (balance < x) {
balance = 0;
System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
} else {
balance -= x;
System.out.println("The deduction of " + x + " from your balance is completed!");
}
}
public void deposit(int x) {
balance += x;
System.out.println("You have made a deposit of " + x + " and your current balance is " + balance);
}
//PIN
public String getPIN() {
return PIN;
}
public void changePIN() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your previous PIN: ");
String tryPIN = input.nextLine();
if (tryPIN.equals(PIN)) {
System.out.print("Please enter your new PIN: ");
String newPIN = input.nextLine();
if (checkPIN(newPIN) == false) {
System.out.println("The PIN is not in the correct format!");
} else {
System.out.println("The PIN has been changed");
PIN = newPIN;
}
} else {
System.out.println("The PIN does not match!");
}
}
protected static boolean checkPIN(String str) {
boolean isValid;
if(str.length() != 4) {
isValid = false;
} else {
try {
int x = Integer.parseInt(str);
isValid = true;
} catch (NumberFormatException e) {
isValid = false;
}
}
return isValid;
}
//Kjo metode duhet per testim
public void getDetails() {
System.out.println(balance + " and PIN " + PIN);
}
}
I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.
I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.
I have provided all the current code on my program and the fix I implemented on FileManagment class

How to fix "looping and candidate voting" error in Java

I'm making a voting system, and want the voting system to loop until the user enters 0 and the candidate that wins will be outputted
two classes
package javaexamcode;
import java.util.Scanner;
public class JavaExamCode {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Nominee mickey = new Nominee("Mickey Mouse");
Nominee donald = new Nominee("Donald Duck");
Nominee minnie = new Nominee("Minnie Mouse");
Nominee goofy = new Nominee("Goofy");
Scanner in = new Scanner(System.in);
while (true) {
System.out.println();
System.out.println("The presidential nominees are:");
System.out.println("1. Mickey Mouse");
System.out.println("2. Donald Duck");
System.out.println("3. Minnie Mouse");
System.out.println("4. Goofy");
System.out.print("What is your vote? ");
try{
int vote=in.nextInt();
if (vote==0){
break;
}else if (vote == 1){
mickey.increaseVote();
}else if (vote == 2){
donald.increaseVote();
}else if (vote == 3){
minnie.increaseVote();
}else if (vote ==4){
goofy.increaseVote();
}
else {
System.out.println("invalid");
}
break;
} catch (Exception e){
System.out.println("Invalid entry, try again");
continue;
}
}
Nominee[] candidates = new Nominee[]{mickey,donald,minnie,goofy};
Nominee president = winner(candidates);
System.out.println("The winner is " + president.toString() + " with " + president.totalVotes() + " votes.");
}
public static Nominee winner(Nominee[] all){
Nominee most = all[0];
for (int i = 1; i < all.length - 1; i++){
if (all[i].totalVotes() > most.totalVotes()){
most = all[i];
}else if (all[i].totalVotes() == most.totalVotes()){
String newName = all[i].toString() + " " + most.toString();
most = new Nominee(newName, (all[i].totalVotes() + most.totalVotes()));
}
}
return most;
}
}
package javaexamcode;
public class Nominee{
private String name;
private int votes;
public Nominee(String name){
this.name = name;
}
public Nominee (String name, int votes){
this.name = name;
this.votes = votes;
}
public void increaseVote(){
votes++;
}
public String toString(){
return name;
}
public int totalVotes(){
return votes;
}
}
There is also an error when you type 4 then it outputs that the winner is mickey and minnie with 0 votes.
Help would be greatly appreciated
I have searched online but could not find much
In your method:
public static Nominee winner(Nominee[] all){
Nominee most = all[0];
for (int i = 1; i < all.length - 1; i++){
if (all[i].totalVotes() > most.totalVotes()){
most = all[i];
}else if (all[i].totalVotes() == most.totalVotes()){
String newName = all[i].toString() + " " + most.toString();
most = new Nominee(newName, (all[i].totalVotes() + most.totalVotes()));
}
}
return most;
}
your for loop is ignoring the last candidate (#4 in this case)
Instead of the looping condition i < all.length - 1 you need to loop to i < all.length instead.

May someone help me check how to create a list?

guys, am doing java programing and try to make a list, but i cannnot let it work as i expected, please help me find out where is wrong.
i have create the code on BlueJ and try to make main and method in different part, but when i try to add a variable in list, it seems added but wont present correctly, and remove method will call error and shut down the whole program
one is :
import java.util.ArrayList;
public class Plane
{
//Create 3 types of variables.
private String name;
private int safelength;
private short station;
private String passengername;
private static int seat;
private static int age;
private ArrayList<Passenger> Passengers;
public Plane(String psgname, int psgseat, int psgage)
{
psgname = passengername;
psgseat = seat;
psgage = age;
Passengers = new ArrayList<Passenger>();
}
public Plane(String planename, int maxlength, short astation)
{
name = planename;
safelength = maxlength;
station = astation;
}
public void addPassenger(Passenger Passenger)
{
Passengers.add(Passenger);
}
public void addPassenger(String passengernames, int pseat, int page)
{
Passengers.add(new Passenger(passengername, seat, page));
}
public Passenger findPassenger(String find)
{
for(Passenger ps : Passengers)
{
if(ps.getpname().contains(find))
{
return ps;
}
}
return null;
}
public int numberofPassenger()
{
return Passengers.size();
}
public void removePassenger(int number)
{
if (number >= 0 && number <numberofPassenger())
{
Passengers.remove(number);
}
}
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
public void setname(String n)
{
name = n;
}
public String getname()
{
return name;
}
public void setsafelength(int s)
{
safelength = s;
}
public int getsafelength()
{
return safelength;
}
public void setstation(short a)
{
station = a;
}
public short getstation()
{
return station;
}
public String toString()
{
String text = "System checked, " + getname() + ", you can prepare yourself at station " + getstation() + " with the maxlength of " + getsafelength() + " metres.";
return text;
}
}
another one is :
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private static String pname;
private static int seat;
private static int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(pname, seat, age);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public static void setpname(String pn)
{
pname = pn;
}
public static String getpname()
{
return pname;
}
}
Problem 1.
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
Here you are printing the value of instance variable,not the passenger's name.To print it, do
System.out.println(Passengers.get(index).getpname());
but this will return null,because your pname is static and you have never initialized its value.For this,change all yor static varibales to non-static.
Problem 2.
Passenger padd = new Passenger(pname, seat, age);
you are storing passenger's name seat age in x y zvariables respectively,butduring the creation of Passenger ,you are using pname seat age variables, which are null.So here do
Passenger padd = new Passenger(x, y, z);
At last,change every static variable and methods to non-static.
Final Solution will look like this,
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private String pname;
private int seat;
private int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(x, y, z);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public void setpname(String pn)
{
pname = pn;
}
public String getpname()
{
return pname;
}
}

Bank Program error when I try to access an account that does not exist

I have been working on this bank program for my Java class at school for the past week and a half. I thought I finally had it working the way my instructor wanted. However, when I try to access an account that does not exist, the program "blows up" (my instructors words). I need it to let the user know that the account does not exist and redirect them back to the main menu. So, my problem I believe is in my findAcct method in my Bank class. I have tried several fixes but none have worked. Any insight or help would be greatly appreciated! I need to have this done by Monday. I know I said the problem is in one method, but I'll post my whole program for context.
Bank Class
import java.util.Scanner;
public class Bank
{
private int max = 25;
private int count;
bankAcct myAcct[] = new bankAcct[max];
Scanner scannerObject = new Scanner(System.in);
public void openAcct()
{
if (count >= max){
System.out.println("Not accepting new customers at this time.");
}else{
System.out.println("Please enter your name: ");
String lname = scannerObject.next();
myAcct[count] = new bankAcct(count + 1, 25, lname);
count++;
System.out.println("Thank you " + lname + ", your account number is: " + count);
}
}
public int findAcct() // This is the method in question
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
found = i;
}
}
return found;
}
public void seeBal()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].dispBal();
}
}
public void Deposit()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].makeDeposit();
}
}
public void Withdrawal()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].makeWithdrawal();
}
}
}
bankAcct Class
import java.util.Scanner;
public class bankAcct
{
private double Bal;
private int acctNum;
private String name;
Scanner scannerObject = new Scanner(System.in);
public bankAcct(int pAcctNum, double pBal, String pName)
{
Bal = pBal;
acctNum = pAcctNum;
name = pName;
}
public void makeDeposit()
{
System.out.print( "Hello " + name + ", please, enter amount to deposit $");
double lDep = scannerObject.nextDouble();
Bal = Bal + lDep;
System.out.println( " You have deposited $" + lDep);
System.out.println( " Your new balance is $" + Bal);
}
public void makeWithdrawal()
{
System.out.print( "Hello " + name + ", please, enter amount to withdraw $");
double lWDraw = scannerObject.nextDouble();
if (lWDraw <= Bal){
Bal = Bal - lWDraw;
System.out.println( "You have withdrawn $" + lWDraw);
System.out.println( "Your new balance is $" + Bal);
}else{
System.out.println("Insufficient funds!");
}
}
public void dispBal()
{
System.out.println( "Hello " + name + ", your current balance is $" + Bal);
}
public int getAcctNum()
{
return acctNum;
}
public void setName(String pName)
{
name = pName;
}
public String getName()
{
return name;
}
}
bankUser Class
import java.util.Scanner;
public class bankUser
{
public static void main(String[] args)
{
Bank myBank = new Bank();
int Choice;
do
{
dispMenu();
Choice = getChoice();
proChoice(Choice, myBank);
}
while (Choice !=0);
}
public static void dispMenu()
{
System.out.println( "|==================================|");
System.out.println( "| TONY'S FIRST NATIONAL BANK |");
System.out.println( "|***********Menu Options***********|");
System.out.println( "|__________________________________|");
System.out.println( "| Press [1] To Open New Account |");
System.out.println( "| Press [2] To View Balance |");
System.out.println( "| Press [3] To Make Deposit |");
System.out.println( "| Press [4] To Make Withdrawal |");
System.out.println( "| Press [0] to Exit |");
System.out.println( "|__________________________________|");
System.out.println( "| Please Make Selection Now... |");
System.out.println( "|==================================|");
}
static int getChoice()
{
Scanner scannerObject = new Scanner(System.in);
int pChoice, Choice;
pChoice = scannerObject.nextInt();
Choice = pChoice;
return Choice;
}
static void proChoice(int Choice, Bank myBank)
{
switch (Choice)
{
case 1: myBank.openAcct();
break;
case 2: myBank.seeBal();
break;
case 3: myBank.Deposit();
break;
case 4: myBank.Withdrawal();
break;
case 0: System.out.println( "Thank you, come again.");
break;
}
}
}
Again, any help would be greatly appreciated. I am still a padawan when it comes to Java.
*UPDATE: I have tried this code, and it seems to work! However, my instructor told me that we can never have 2 return statements within a method.
public int findAcct()
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
return found = i;
}
}
return -1;
}
UPDATE: Here is what I did to my findAcct method in my Bank Class:
public int findAcct()
{
System.out.println("Greetings, please enter your account number: ");
int acctNum = scannerObject.nextInt();
int found = -1;
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == acctNum){
found = i;
break; //Ends Loop
}
}
return found;
}
My instructor did not mind a break statement, so I added out at the end of my for loop. I also moved my local variable found = -1; down a couple lines. Thank you for all the help! I can't wait to learn more!
If you do not want to have 2 return statements within a method (which you can have, but sometimes it is bad practice when you are beginning coding so professors like to just make that rule) you can use your found variable to store the value that will be returned and return found at the end of the function.
You were on the right track.
Example:
public int findAcct()
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
found = i;
break; //Exit out of the loop
}
}
return found;
}
This code will set found to i if it finds the account and then break out of the loop. After it breaks out of the loop it will return found. Otherwise, found will never be set and return -1 since you initialized it to -1 at the top.
If your instructor has not taught you break statements yet, then you can use a boolean variable foundAccount initialized to false. Then check if foundAccount is false before doing your if statement check. Once you find it, set it to true so you do not keep looking.
Example:
public int findAcct()
{
int found = -1;
boolean foundMatch = false;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(!foundMatch){
if(myAcct[i].getAcctNum() == found){
found = i;
foundMatch = true; //we will no longer search
}
}
}
return found;
}

How to connect multiple ArrayLists in different classes. (Bank program in java)

I'm involved in a group assignment where we are supposed to create a bank program. This is our first time programming in java. We are stuck and we are having trouble figuring out how to connect our customer and account classes. They both consist of ArrayLists and we want the customer arraylists to contain the accounts. So that if we delete a customer, the accounts that belong to that customer will also be deleted. Can anyone give us a push in the right direction?
This is our main class which contains the bank menu:
package bank6;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Bankmenu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Customer client = new Customer();
Account bank = new Account();
Account accs = new Account();
Customer cust1, cust2, cust3;
cust1 = new Customer("8905060000", "Henrik");
cust2 = new Customer("8910210000", "Emelie");
cust3 = new Customer("8611040000", "Fredrik");
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
client.addCustomerAr(cust1);
client.addCustomerAr(cust2);
client.addCustomerAr(cust3);
int ChoiceOne = 0;
int CustChoice;
int currentCustomer;
int currentAccount;
int amountC;
int amountD;
int editCust;
String personNummer = null;
String Pnr = "0";
int AdminChoice;
/*prompts the user to set ChoiceOne equal to 1 or 2. Hasnextint checks
if the input is an int. else asks for new input. */
while (ChoiceOne != 1 && ChoiceOne != 2) {
System.out.println("Press 1 to login as customer or 2 to login as admin ");
if (input.hasNextInt()) {
ChoiceOne = input.nextInt();
System.out.println();
} else {
System.out.println("You must enter number 1 or number 2");
input.next();
}//ends else
}//ends while
/*
If the user chooses 1 in the previous question, the user will be sent to
the interface for the customer. User is then asked to enter his social
security number and this number will be checked using the Luhn algoritm. Since
the scanner input is already used we added a new Scanner calleds nexLine
to deal with custPnr as a string.
(http://stackoverflow.com/questions/5032356/using-scanner-nextline)
*/
if (ChoiceOne == 1) {
//boolean quit=false;
while ("0".equals(Pnr)) {
// System.out.println("Welcome customer. Please login by using your birthdate (yymmddnnnn) ");
// Scanner nextLine = new Scanner(System.in);
// Pnr = nextLine.nextLine();
//Luhn.checkLogin(Pnr);
//Här måste en kontroll med Luhn algoritmen göras.
// getUserBirthdate();
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
/* }
Sets "quit" to false and executes quit=true if customer chooses case 0
*/
}
boolean quit = false;
do {
// boolean quit = false;
//System.out.println();
System.out.println("Logged on as " + personNummer);
System.out.println("1. deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
CustChoice = input.nextInt();
switch (CustChoice) {
case 1: //Deposit money
System.out.println(bank.getAccountNumbersFor(personNummer));
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to deposit:");
amountC = input.nextInt();
System.out.println(bank.creditAccount(currentAccount, amountC));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 2://Withdraw money
// System.out.println(bank.getAccNosFor(custPnr));
bank.getAccountNo();
System.out.println("Enter account number:");
currentAccount = input.nextInt();
System.out.println("Enter amount to withdraw:");
amountD = input.nextInt();
System.out.println(bank.debitAccount(currentAccount, amountD));
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 3://Check ballance and accounts
System.out.println(bank.getAccountNumbersFor("Henrik"));
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends if
else if (ChoiceOne == 2) {
while ("0".equals(Pnr)) {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner(System.in);
personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
break;
}
//AdminpNr = input.nextInt();
//Här måste en kontroll av AdminpNr göras med hjälp av Luhn.
boolean quit = false;
do {
System.out.println("1. Add customer");
System.out.println("2. Add account");
System.out.println("3. List customer");
System.out.println("4. List accounts");
System.out.println("5. Remove customer");
System.out.println("6. Remove account");
System.out.print("Your choice, 0 to quit: ");
AdminChoice = input.nextInt();
switch (AdminChoice) {
case 1://add customer
int i = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<String, Customer> testCustomers = new HashMap<String, Customer>();
String name = scan.nextLine();
//System.out.println("Att arbeta på bank ska vara jobbigt, skriv in det igen:");
//String pnummer = scan.nextLine();
String pnummer = name;
System.out.println("Skriv in namn:");
String kundnamn = scan.nextLine();
Customer obj = new Customer(pnummer, kundnamn);
testCustomers.put(name, obj);
client.addCustomerAr(obj);
i++;
} while (i < 2);
break;
case 2://add account
int i2 = 0;
do {
System.out.println("Skriv in nytt personnummer:");
Scanner scan = new Scanner(System.in);
Map<Long, Account> testAccs = new HashMap<Long, Account>();
Long name = scan.nextLong();
//System.out.println("Skriv in personnummer igen:");
Long own = name;
long bal = 0;
Account obt = new Account(own, bal);
testAccs.put(name, obt);
accs.addAccAr(obt);
i2++;
} while (i2 < 2);
break;
case 3:// List customer and accounts
for (String info : client.getAllClients()) {
System.out.println(info);
}
break;
case 4:
for (Long infoAcc : accs.getAllAccounts()) {
System.out.println(infoAcc);
}
break;
case 5:
// ta bort kund
break;
case 6:
// ta bort konto
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}//ends else if
}//ends main
/* private static void getUserBirthdate() {
boolean CorrectBirthDate = false;
while (CorrectBirthDate == false) {
System.out.println("Please enter your birthdate");
Scanner inception = new Scanner (System.in);
String personNummer = inception.next();
CorrectBirthDate = Luhn.checkLogin(personNummer);
if (CorrectBirthDate == false) {
System.out.println("Incorrect birthdate. You will be prompted to type it again");
}
}
}
*/
}//ends class
This is our Account class;
package bank6;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class Account {
private ArrayList accounts;
private Object lastAcc;
public String customerSocial;
private Integer balance;
private Integer accountNumber;
private Customer owner;
private Account Customer6; // Association customer/account.
private ArrayList<Account> myAccounts = new ArrayList<Account>();
public Integer deposit;
public Integer withdraw;
static Integer accountNo = 1010;
private Long persnr;
private long balans = 0;
/*Constructor.. A account cannot exist unless it is owned by a customer*/
public Account(Customer owner, Integer balance) {
this.owner = owner;
this.balance = balance;
accountNumber = accountNo++;
}
public Account() {
accounts = new ArrayList();
}
public Account(Long persnr, long balans) {
this.persnr = persnr;
this.balans = balans;
accountNumber = accountNo++;
}
public Integer getAccountNo() {
return accountNumber;
}
public String getOwner() {
return owner.getName();
}
public Customer getOwn() {
return owner;
}
public Integer getBalance() {
return balance;
}
//credits the account with an amount of money and returns a string
public String credit(Integer anAmount) {
balance += anAmount;
// return "Account number " + accountNumber + " Has been credited with "+anAmount + " kr.";
return " " + anAmount + " kr has been deposited to " + accountNumber + "\n";
}
public boolean canDebit(Integer anAmount) {
return anAmount <= balance;
}
public String debit(Integer anAmount) {
if (this.canDebit(anAmount)) {
balance -= anAmount;
return " " + anAmount + " kr has been withdrawn from " + accountNumber + "\n";
} else {
return "Account number" + accountNo + "has insufficient funds to debit"
+ anAmount;
}
}
public void addNewAccount(Customer customer) {
accounts.add(new Account(customer, 0));
lastAcc = accounts.get(accounts.size() - 1);
System.out.println("*** New account created. ***" //+ lastAcc
+ "\n");
}
public String removeAccount(int accountNumber) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
found = true; //there is a match stop the loop
if (account.getBalance() == 0) {
iter.remove();//remove this account object
results = "Account number " + accountNumber + " has been removed";
} else {
results = "Account number " + accountNumber + " cannot be removed"
+ "as it has a balance of: " + account.getBalance();
}
}//ends if there is a match
}// end while loop
if (!found) {
results = "No such account";
}
return results;
}
public String creditAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.credit(anAmount);
found = true;//stop the loop
}
}
if (!found) {
results = "No such customer";
}
return results;
}
public String debitAccount(int accountNumber, Integer anAmount) {
boolean found = false;
String results = "";
ListIterator iter = accounts.listIterator();
while (iter.hasNext() && !found) {
Account account = (Account) iter.next();
if (account.getAccountNo() == accountNumber) {
results = account.debit(anAmount);
found = true;
}
}
if (!found) {
results = "No such Customer";
}
return results;
}
public String getAccountNumbersFor(String CustomerName) {
String details = CustomerName + " has the followinng accounts: "
+ "\n\n";
Iterator iter = accounts.iterator();
//visit all of the accounts in the ArrayList
while (iter.hasNext()) {
Account account = (Account) iter.next();
if (account.getOwner().equals(CustomerName)) {
details += " Account number " + account.getAccountNo()
+ " Balance " + account.getBalance() + "kr \n";
}//ends if
}//ends while
return details;
}
public String bankAccounts() {
String details = "ALL BANK ACCOUNTS" + "\n"
+ "-----------------" + '\n';
if (accounts.size() == 0) {
details += "There are no bank accounts";
} else {
Iterator iter = accounts.iterator();
while (iter.hasNext()) {
details += iter.next().toString() + '\n';
}
}
return details;
}
#Override
public String toString() {
return "Account " + accountNumber + ": " + owner
+ "\nBalance: " + balance + " kr.\n";
}
public Boolean authenticateUser(String login, String ssn) {
if (Luhn.checkLogin(ssn)) {
System.out.println("User authenticated");
return true;
} else {
System.out.println("Authentication refused");
return false;
}
}
public void addAccAr(Account myAccount) {
myAccounts.add(myAccount);
}
public Long getBalanceToLong() {
long balTemp = balans;
return balTemp;
}
public Long getPnTorLong() {
return persnr;
}
public Long getAccNoLong() {
long accTemp = accountNumber;
return accTemp;
}
public ArrayList<Long> getAllAccounts() {
ArrayList<Long> allAccounts = new ArrayList<>();
System.out.println("ALL ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
allAccounts.add(myAccount.getAccNoLong());
allAccounts.add(myAccount.getPnTorLong());
allAccounts.add(myAccount.getBalanceToLong());
}
return allAccounts;
}
/*
public ArrayList<String> getMyAccounts() {
ArrayList<String> ownAccounts = new ArrayList<>();
System.out.println("MY ACCOUNTS\n-----------");
for (Account myAccount : myAccounts) {
ownAccounts.add(myAccount.getAccNoStr());
ownAccounts.add(myAccount.getBalanceToStr());
}
return ownAccounts;
}*/
}
This is our Customer class
package bank6;
import java.util.ArrayList;
public class Customer {
int custCounter;
//attribut
private Long socialNo;
private String name;
private ArrayList customers;
public Integer customerNumber;
static Integer custNo = 1;
private ArrayList<Customer> clients = new ArrayList<Customer>();
//konstruktor
public Customer(String socialStr, String name) {
Long socialTemp = new Long(socialStr);
this.name = name;
this.socialNo = socialTemp;
customerNumber = custNo++;
}//ends konstruktor customer6
public Customer() {
customers = new ArrayList();
}
/* Set methods*/
public void setName(String name) {
this.name = name;
}
public void setsocialNo(Long socialNo) {
this.socialNo = socialNo;
}
/* get methods */
public String getName() {
return name;
}
public String getSocialNoStr() {
String socialTemp = Long.toString(socialNo);
return socialTemp;
}
public Long getSocialNo() {
return socialNo;
}
/*toString() method*/
#Override
public String toString() {
return "\n" + "Owner: " + name + " (" + socialNo + ")";
}
public void addAccCustAr() {
}
public void addCustomerAr(Customer client) {
clients.add(client);
}
public ArrayList<String> getAllClients() {
ArrayList<String> allClients = new ArrayList<>();
System.out.println("ALL CLIENTS\n-----------");
for (Customer client : clients) {
allClients.add(client.getName());
allClients.add(client.getSocialNoStr() + "\n");
}
return allClients;
//add account
//public void addAccount(account6 account){
// accounts.add(account);
//}// ends adds account
//remove account
//public void removeAccount (account6 account) {
// accounts.remove(account);
//}//ends remove account
}
}//ends public class
This is our Luhn class
package bank6;
public class Luhn {
public static boolean checkLogin(String pnr) {
if (pnr.length() != 10) {
System.out.println("");
return false;
} else {
int length = pnr.length();
int sum = 0;
int pos = length - 1;
for (int i = 1; i <= length; i++, pos--) {
char tmp = pnr.charAt(pos);
int num = Integer.parseInt(String.valueOf(tmp));
int produkt;
if (i % 2 != 0) {
produkt = num * 1;
} else {
produkt = num * 2;
}
if (produkt > 9) {
produkt -= 9;
}
sum += produkt;
}
boolean korrekt = (sum % 10) == 0;
if (korrekt) {
System.out.println("Correct");
return true;
} else {
System.out.println("Invalid");
return false;
}
}
}
}
Your Account class already has a Customer field -- good.
You should give Customer an ArrayList<Account> accounts field.
And also give Customer addAccount(Account acct) and removeAccount(Account acct) methods.
Why does Customer have an ArrayList<Customer> field? That makes little sense. Should a Customer hold a list of other Customers? Why? For what purpose?
Why does Account have private ArrayList<Account> myAccounts = new ArrayList<Account>();? That also makes little sense. Should an Account hold a bunch of other Accounts? Again, for what purpose?
The Account class should logically represent one and only one Account.
Same for the Customer class -- it should logically represent only one Customer.
If you think through things logically, they usually come together, and each component of your code should make sense. If it doesn't, question why it is there.
So this code is broken:
Account bank = new Account();
//....
bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);
Since you're adding a bunch of Customer's to an Account object. It looks like you should have another class, a Bank class, one that can hold an ArrayList<Customer>. Wouldn't this make sense?

Categories