Having problems now, i changed it to accept try and catch and now its not finding the sales ID to compare.
Is anyone able to see what is happening?
has it got something to do with how getSaleID is called?
private static void submitOffer() throws OfferException
{
int offerPrice;
boolean offerAccepted;
System.out.print("Enter sale ID: ");
String saleID = keyboard.nextLine();
try
{
for (int i = 0; i < salesCount; i++)
{
if ( sales[i].getSaleID().equalsIgnoreCase(saleID))
{
System.out.print("Enter offer price: ");
offerPrice = keyboard.nextInt();
keyboard.nextLine();
System.out.println();
//try!!!
offerAccepted = sales[i].makeOffer(offerPrice);
if (offerAccepted == true)
{
System.out.print("Offer was accepted");
if(offerPrice <= sales[i].getReservePrice())
{
System.out.print("Reserve Price was met");
}
else
{
System.out.print("Reserve Price was not met");
}
}
else
{
System.out.print("Offer was not accepted");
}
}
} // for
}
catch(OfferException e)
{
System.out.print("That property with the sale ID " + saleID + "Does not exist");
System.out.println();
}
}
Related
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
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In my programming class I was asked to make a list of enrolling students with information inside each one, and display all entered students with an average off their grades and if they were admitted to the school or not. everything works fine except when I get to my for loop at the end of the program to display the info of each student and their average, the program simply ends before displaying any info on the students and gives no error messages.
Please help!!
Main Class:
public class MainStudent {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
List<Student> students = new ArrayList<Student>();
String FullName;
String answer;
System.out.println("Welcome! Please enroll your students");
System.out.println("");
do {
Student student = new Student();
System.out.println("Please enter the first name of the student");
student.setFirstName(scan.next());
System.out.println("");
System.out.println("Please enter the last name of the student");
student.setLastName(scan.next());
System.out.println("");
FullName = student.getFirstName() + " " + student.getLastName();
Boolean validation = false;
while (validation == false) {
System.out.println("Please enter the ID of " + FullName);
try {
student.setID(scan.nextInt());
validation = true;
}
catch(Exception e) {
System.out.println("please enter only numbers");
System.out.println("");
validation = false;
scan.next();
}
}
System.out.println("");
System.out.println("Please enter the gender of " + FullName);
student.setGender(scan.next());
System.out.println("");
System.out.println("Please enter the age of " + FullName);
student.setAge(scan.nextInt());
if (student.getAge() > 17) {
do {
System.out.println("");
System.out.println("Please enter the first score of " + FullName);
try {
student.setScore1(scan.nextInt());
if (student.getScore1() > 100 || student.getScore1() < 0) {
System.out.println("please enter a positive number below 100");
validation = false;
}
else {
validation = true;
}
}
catch (Exception e) {
System.out.println("Please only enter numbers");
validation = false;
scan.next();
}
}
while (validation == false);
System.out.println("");
do {
System.out.println("Please enter the second score of " + FullName);
try {
student.setScore2(scan.nextInt());
if (student.getScore2() > 100 || student.getScore2() < 0) {
System.out.println("please enter a positive number below 100");
validation = false;
}
else {
validation = true;
}
}
catch (Exception e) {
System.out.println("Please only enter numbers");
validation = false;
scan.next();
}
}
while (validation == false);
System.out.println("");
do {
System.out.println("Please enter the third score of " + FullName);
try {
student.setScore3(scan.nextInt());
if (student.getScore3() > 100 || student.getScore3() < 0) {
System.out.println("please enter a positive number below 100");
validation = false;
}
else {
validation = true;
}
}
catch (Exception e) {
System.out.println("Please only enter numbers");
validation = false;
scan.next();
}
}
while (validation == false);
System.out.println("");
do {
System.out.println("Please enter the fourth score of " + FullName);
try {
student.setScore4(scan.nextInt());
if (student.getScore4() > 100 || student.getScore4() < 0) {
System.out.println("please enter a positive number below 100");
validation = false;
}
else {
validation = true;
}
}
catch (Exception e) {
System.out.println("Please only enter numbers");
validation = false;
scan.next();
}
}
while (validation == false);
}
else {
System.out.println("You can not enroll a student under the age of 18");
student.setScore1(0);
student.setScore2(0);
student.setScore3(0);
student.setScore4(0);
}
System.out.println("Do you want to register another student? \n Answer with Y/N");
answer = scan.next();
}
while (answer.equals("Y") || answer.equals("y"));
for (int i = 0; i < students.size(); i++) {
System.out.println("");
System.out.println("*******************************");
System.out.println("Name: " + students.get(i).getFirstName());
System.out.println("Age: " + students.get(i).getAge() );
System.out.println("Gender: " + students.get(i).getGender());
System.out.println("Scored Average: " + students.get(i).Average(i, i, i, i));
System.out.println(students.get(i).Enrolled(i));
System.out.println("*******************************");
}
scan.close();
}
}
The loop doesn't run because you aren't actually adding anything to the array list called "students". You might want to start adding stuff inside that list inside the do-while loops, so that students.size() is not equal to 0.
I know it's a silly silly program. It's just to practice constructors.
public class PetRecord {
private String name = "Bob";
private int age;
private double weight;
public PetRecord(String initialName, int initialAge, double initialWeight) {
name = initialName;
if(initialAge < 0 || weight < 0) {
System.out.println("Error: Age or weight cannot be negative");
System.exit(0);
}
else {
age = initialAge;
weight = initialWeight;
}
}
public PetRecord(String initialName) {
name = initialName;
}
public void output() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
}
public void setAll(String newName, int newAge, double newWeight) {
name = newName;
if ((newAge < 0) || (newWeight < 0)) {
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else {
age = newAge;
weight = newWeight;
}
}
public void review() {
if(age < 8 && weight < 8) {
System.out.println("Your pets weight and age are healthy.");
}
if(age >= 8 && weight >=8) {
System.out.println("Your pets weight and age are unhealthy.");
}
else {
System.out.println("Come to my office for a proper assessment.");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PetRecord d = new PetRecord("Bob");
System.out.println("Please check if our current records are correct.");
d.output();
System.out.println("Are they correct?");
String answer = input.nextLine();
String yes = "Yes";
String no = "No";
if((answer.equals(yes))) {
System.exit(0);
}
if(answer.equals(no)) {
System.out.println("Please enter your pets name.");
String correctName = input.nextLine();
System.out.println("Age?");
int correctAge = input.nextInt();
System.out.println("Weight?");
double correctWeight = input.nextDouble();
d.setAll(correctName, correctAge, correctWeight);
System.out.println("Your updated records say: ");
d.output();
System.out.println("Would you like a health review?");
String answer1 = input.nextLine();
String yes1 = "yes";
String no1 = "no";
if(answer1.equals(yes1)) {
d.review();
}
if(answer1.equals(no1)) {
System.out.println("Thank you for using PetSystem. Goodbye.");
System.exit(0);
}
}
}
}
My program accepts input for String answer, but my program will not accept String answer1. I can't even type anything in the console after the program asks you if you would like a health review.
The issue comes from here
System.out.println("Your updated records say: ");
d.output();
Because you have printed something out in the middle of accepting input, you most likely have an extra newline token you have not dealt with. Prior to asking the "health review" question place the following code.
while (input.hasNextLine()) {
input.nextLine();
}
This will make sure that you clear out any extra tokens before continuing to accept user input.
you can,t type anything in the console after "if you would like a health review." because you code only runs ones you should put it in a loop to make it run more than once
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;
}
The problem is when I create three accounts for example 1, 2 and 3. Then delete 2 and add a new one the result is 1, 3 and 2, everything ok. When I add another account the results is 1, 3, 2, 3. Adding yet another one gets me 1, 3, 2, 3, 4.
The values are stored in a text file from where the array reads and writes them to.
The problem is I get the same account number twice. Also just making it always increment by one isn't ok, because I need it to fill the gaps from the deleted accounts.
Can't figure out the problem and would really appreciate some help!
The code responsible:
private int choice;
public String name;
public int accountNr = 1;
public int cash;
public int funds;
private boolean run = true;
private int index = 0;
private int index1 = 0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
ArrayList<Account> acc = new ArrayList<Account>();
ArrayList<TransferHistory> transferHistory = new ArrayList<TransferHistory>();
public int c;
public int amount;
private int c1;
private int size;
ReaderWriter io = new ReaderWriter();
private int account0;
private Account ac;
private int account1;
private int account3;
private int account2;
private int viewAnswer;
private int deleteAnswer;
private String s = "";
public void startMessage() {
System.out.println("***** Welcome to our bank system *****");
}
public void mainMenu() {
while (run == true) {
acc = io.readFromFile();
Scanner scan = new Scanner(System.in);
System.out.println("**** Main menu ****");
System.out.println("1. Create a new account");
System.out.println("2. Deposit/Withdraw from account");
System.out.println("3. Transfer money");
System.out.println("4. View the account properties");
System.out.println("5. View one account properties");
System.out.println("6. Delete account");
System.out.println("7. Show transfer history");
System.out.println("8. Show transfer history for one account");
System.out.println("9. Quit");
try {
choice = scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter valid choice");
}
if (choice == 1) {
addAccount();
}
if (choice == 2) {
transfer();
}
if (choice == 3) {
transferWithin();
}
if (choice == 4) {
view();
}
if (choice == 5) {
viewOne();
}
if (choice == 6) {
delete();
}
if (choice == 7) {
showTransfers();
}
if (choice == 8) {
showOneTransfer();
}
if (choice == 9) {
quit();
}
}
}
public void addAccount() {
System.out.print("Enter your name: ");
name = scan.next();
for (int i = 0; i < acc.size(); i++) {
if(acc.get(i).getAcc() == accountNr) {
accountNr++;
}
}
System.out.println("Your account nr is: " + accountNr);
System.out.print("Enter your starting funds: ");
try {
cash = scan.nextInt();
if(cash < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
index = acc.size();
acc.add(index, new Account(name, accountNr, cash)); //Add new account object to specified element in acc arraylist
index = acc.size();
io.writeToFile(acc);
} catch (InputMismatchException e) {
System.out.println("The scanner couldn´t read your input, use digits next time.");
System.out.println("The funds for this account has been set to zero, use transfers to adjust");
scan.reset();
}
}
public void transfer() {
System.out.print("Enter account number to withdraw/deposit to: ");
try {
account1 = Integer.parseInt(scan.nextLine());
if(account1 > acc.size() || account1 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a number!");
scan.reset();
return;
}
System.out.print("Enter a positive number to deposit and negative to withdraw: ");
try {
funds = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println("Enter a number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (account1 == i) {
if (funds > 0) {
acc.get(account1 - 1).setCash(funds + acc.get(account1 - 1).getCash());
System.out.println("The amount is changed to " + acc.get(account1 - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account1, funds, account1));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
}
if (funds < 0 && funds + acc.get(account1 - 1).getCash() > 0) {
acc.get(account1 - 1).setCash(funds + acc.get(account1 - 1).getCash());
System.out.println("The amount is changed to " + acc.get(account1 - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account1, funds, account1));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
} else if (acc.get(account1 - 1).getCash() + funds < 0) {
System.out.println("This transaction is not allowed since the balance will be negative");
}
}
}
io.writeToFile(acc);
}
public void view() {
acc = io.readFromFile();
for (int i = 0; i < acc.size(); i++) {
System.out.println(s);
System.out.println("Account name: " + acc.get(i).tempName);
System.out.println("Account number: " + acc.get(i).tempAccNr);
System.out.println("Funds: " + acc.get(i).tempCash);
}
if (acc.isEmpty()) {
System.out.println("No accounts to show");
}
}
public void quit() {
System.exit(0);
}
private void transferWithin() {
System.out.print("Enter account you want to transfer from: ");
try {
account3 = Integer.parseInt(scan.nextLine());
if(account3 > acc.size() || account3 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.print("Enter a account number: ");
scan.reset();
return;
}
System.out.print("Enter amount you want to transfer: ");
try {
amount = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.print("Enter a number: ");
scan.reset();
return;
}
System.out.print("Enter account you want to transfer to: ");
try {
account2 = Integer.parseInt(scan.nextLine());
if(account2 > acc.size() || account2 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.print("Enter a account number:");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (i == account3) {
c = acc.get(i - 1).getCash();
if (c - amount >= 0) {
acc.get(i - 1).setCash(c - amount);
System.out.println("Funds in account: " + acc.get(i - 1).getAcc() + " " + acc.get(i - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account3, amount, account2));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
} else if (c - amount < 0) {
System.out.println("Not enough funds in account");
mainMenu();
}
}
}
for (int j = 0; j < acc.size() + 1; j++) {
if (j == account2) {
c1 = acc.get(j - 1).getCash();
acc.get(j - 1).setCash(c1 + amount);
System.out.println("Funds in account " + acc.get(j - 1).getAcc() + " " + acc.get(j - 1).getCash());
}
}
io.writeToFile(acc);
}
private void viewOne() {
System.out.println("Enter account number you want to look at");
try {
viewAnswer = Integer.parseInt(scan.nextLine());
if(viewAnswer > acc.size() || viewAnswer <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (i == viewAnswer) {
System.out.println("Account name: " + acc.get(i - 1).getName());
System.out.println("Account nr: " + acc.get(i - 1).getAcc());
System.out.println("Funds: " + acc.get(i - 1).getCash());
}
}
}
private void delete() {
System.out.print("Enter account you want to delete: ");
try {
deleteAnswer = Integer.parseInt(scan.nextLine());
if(deleteAnswer > acc.size() || deleteAnswer < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size(); i++) {
if (acc.get(i).getAcc() == deleteAnswer) {
acc.remove(i);
io.writeToFile(acc);
}
}
}
private void showTransfers() {
transferHistory = io.readTransferedFromFile();
System.out.println(s);
System.out.println("***Transactions***");
System.out.println(s);
for (int i = 0; i < transferHistory.size(); i++) {
int t = transferHistory.get(i).tempFromAccount;
int t1 = transferHistory.get(i).temptransfered;
int t2 = transferHistory.get(i).tempToAccount;
System.out.println("Transfer from: " + t);
System.out.println("Transfered amount: " + t1);
System.out.println("Transfered to: " + t2);
System.out.println(s);
}
}
private void showOneTransfer() {
transferHistory = io.readTransferedFromFile();
System.out.println(s);
System.out.println("***Transactions***");
System.out.println(s);
System.out.print("Enter account nr: ");
int z = scan.nextInt();
System.out.println("Transactions made my account nr "+z+":");
for (int i = 0; i < transferHistory.size(); i++) {
if(transferHistory.get(i).tempFromAccount == z){
int t = transferHistory.get(i).tempFromAccount;
int t1 = transferHistory.get(i).temptransfered;
int t2 = transferHistory.get(i).tempToAccount;
System.out.println("Transfer from: " + t);
System.out.println("Transfered amount: " + t1);
System.out.println("Transfered to: " + t2);
System.out.println(s);
}
}
}
}
Here I populate the array from the file:
public ArrayList<Account> readFromFile() {
FileReader reader = null;
ArrayList<Account> result = new ArrayList<Account>();
try {
reader = new FileReader(new File(text));
BufferedReader br = new BufferedReader(reader);
String row = br.readLine();
while (row != null) {
String[] splits = row.split(":");
if (splits.length == 3) {
int saveNR = Integer.valueOf(splits[1]);
int saveAmount = Integer.valueOf(splits[2]);
String saveName = splits[0];
result.add(new Account(saveName,saveNR,saveAmount));
} else {
System.out.println("Error in file format");
}
row = br.readLine();
}
} catch (Exception e) {
System.out.println("Error while reading from file");
} finally {
try {
reader.close();
} catch (IOException ex) {
System.out.println("Ignore");
}
return result;
}
}
private void delete() {
System.out.print("Enter account you want to delete: ");
try {
deleteAnswer = Integer.parseInt(scan.nextLine());
if(deleteAnswer > acc.size() || deleteAnswer < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size(); i++) {
if (acc.get(i).getAcc() == deleteAnswer) {
acc.remove(i);
io.writeToFile(acc);
}
}
}
If you want a counter, have it be a static variable on the class and increment it when you need a new value. Something like:
private static int counter = 0;
private static int nextCounter() {
return ++counter;
}
Or, for synchronization reasons, use
private static AtomicInteger counter = new AtomicInteger();
private static int nextCounter() {
return counter.incrementAndGet();
}
However, I suggest you stop thinking that you need to fill in all the gaps in the account numbers. Typically in database work, account numbers are never reused. You aren't formally using a database, but you should work the same way. Reuse buys you nothing, and there is always a chance your code may confuse a new user 17 with the an old user 17. Just imagine what would happen were the US Social Security Administration were to reuse social security numbers.
Here's the reason for your error, by the way. In the code:
for (int i = 0; i < acc.size(); i++) {
if(acc.get(i).getAcc() == accountNr) {
accountNr++;
}
}
Suppose accountNr starts as 1, there are 3 accounts, and they have account numbers 2, 1, 3. After each runthrough of the loop, accountNr changes to:
1 ⇢ 1⇢ 2 ⇢ 2.
2 is an existing accont number, but your code sets account number to 2 after the last time it would be checked.
Getting the first unused integer
You want a way to get the first unused integer in acc. Here goes:
private int firstUnusedId(List<Account> accounts) {
List<Integer> ids = new ArrayList<>();
// Foreach loop.
for(Account account: accounts) {
ids.add(account.getAcc());
}
Collections.sort(ids);
for (int index = 0; index < ids.size(); ++index) {
if (ids.get(index) != index + 1) {
return index + 1;
}
}
return ids.size() + 1;
}
If the ids are 2, 1, 5 then they sort to 1, 2, 5. Then the loop compares:
index = 0, index + 1 = 1, compare to 1, equal.
index = 1, index + 1 = 2, compare to 2, equal.
index = 2, index + 1 = 3, compare to 5, not equal, return 3.
If the ids were 3, 2, 1, they would sort to 1, 2, 3, and the only difference would be the last comparison:
index = 2, index + 1 = 3, compare to 3, equal.
return size + 1 = 4.
You must share more of you code but from what i have seen and predict that you are creating the new account from the last accountNr +1 so if your last account in the list is 2 then 3 will be created ...4 etc..so review your new account and set your accountNr = acc.size+1