Java Assignment issue Switch - java

I have an assignment where I have to create an ATM. The program is running, but it seems as if I have an issue because my balance continuously reads $100. I'm not sure where I went wrong in the code. There might be something wrong in my if statement, or in my switch, but I am not sure what I am doing wrong. I have looked over this code for hours, but I seem to just miss the error.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ATMDemo {
public static void main(String[] args) throws IOException {
Account[] accounts = new Account[10];
for(int i=0; i<10; i++) {
accounts[i] = new Account(100,5);
}
System.out.println("Enter Id (0-9)");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int id = Integer.parseInt(br.readLine());
while(!(id>=0 && id <10)) {
System.out.println("Wrong Id, enter again");
id = Integer.parseInt(br.readLine());
}
printMenu();
int c = Integer.parseInt(br.readLine());
while (c!=4) {
switch (c) {
case 1:
System.out.println("Balance : " + accounts[id].getBalance());
break;
case 2:
System.out.println("Enter amount");
double amt = Double.parseDouble(br.readLine());
accounts[id].withdraw(amt);
break;
case 3:
System.out.println("Enter amount");
double amt1 = Double.parseDouble(br.readLine());
accounts[id].deposit(amt1);
break;
}
}
if (c==4) {
System.out.println("Program exited!!!");
}
}
public static void printMenu() {
System.out.println("Enter a choice: \n " +
"1) check balance,\n" +
"2) withdraw,\n" +
"3) deposit, and \n" +
"4) exit");
}
}
class Account {
double balance;
double transaction[][];
int tCount;
int size;
public Account(double balance, int size) {
this.balance = balance;
this.transaction = new double[size][2];
this.tCount = 0;
this.size= size;
}
public void deposit(double amt) {
if(amt>0) {
transact(amt);
} else {
System.out.println("Amount should be > 0 to deposit");
}
}
public void withdraw(double amt) {
if(amt<=balance) {
transact(amt*-1);
} else {
System.out.println("Insufficient Balance");
}
}
public void print() {
for(int i=0; i<tCount; i++) {
System.out.println(transaction[i][0] +", "+ transaction[i][1]);
}
System.out.println("Current available balance :"+balance);
}
public int count() {
return transaction.length;
}
public int count(double base) {
int count = 0;
for(int i=0; i<tCount; i++) {
if(transaction[i][0]<0) {
double amt = -1 * transaction[i][0];
if(amt > base) {
count++;
}
}
}
return count;
}
public void transact(double val) {
if(tCount+1>size)
resize();
balance = balance + val;
transaction[tCount][0] = val;
transaction[tCount][1] = balance;
tCount++;
}
public void resize() {
double[][] tNew = new double[this.size+10][2];
for(int i=0; i<tCount; i++) {
tNew[i] = transaction[i];
}
this.size = this.size + 10;
this.transaction = tNew;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double[][] getTransaction() {
return transaction;
}
public void setTransaction(double[][] transaction) {
this.transaction = transaction;
}
}

Move
printMenu();
int c = Integer.parseInt(br.readLine());
just below
while (c!=4) {
That would make the application pause and ask for input after it performs and action. Right now it just asks once, c becomes 1 and the endless while loops just starts because the value of c is never changed again.

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

In my shop project, my method "checkout" runs several times before stopping when it should only run once when called upon form direct

import java.util.*;
public class Shop {
protected String name;
protected double price;
protected int amount;
protected double discountAmt;
protected double discount;
protected boolean setupComp = false;
protected boolean buyComp = false;
public static void main(String[] args) {
Shop direct = new Shop();
direct.direct();
}
public void direct(){
println("This program supports 4 functions:");
println("\t*Setup Shop");
println("\t*Buy Items");
println("\t*List of items purchased");
println("\t*Checkout");
print("Please choose the function you want: ");
Scanner input = new Scanner(System.in);
int func = input.nextInt();
if (func == 1){
setup();
}
if (func == 2){
buy();
}
if (func == 3){
listItems();
}
1. Everything seems to run fine up to this point, then checkout repeatedly runs a couple of times.
2. I don't know if the problem is how I'm calling upon checkout() or if it is within checkout itself:
if (func == 4);{
checkout();
}
if (func >= 5){
println("Error: do not know " + func);
direct();
}
}
public Shop(){
name = "";
price = 0;
amount = 0;
}
public Shop[] product;
private static void println(String string) {
System.out.println(string);
}
private static void print(String string) {
System.out.print(string);
}
public void setup(){
print("Please enter the number of items: ");
Scanner input = new Scanner(System.in);
int max = input.nextInt();
product = new Shop[max];
for (int i = 0; i < max; i++){
product[i] = new Shop();
print("Enter name of product " + i + ": ");
product[i].setName(name = input.next());
print("Enter the price of the product: ");
product[i].setPrice(price = input.nextDouble());
}
print("Please enter the amount to qualify for discount: ");
this.discountAmt = input.nextDouble();
print("Please enter the discount rate(0.1 for 10%): ");
this.discount = input.nextDouble();
setupComp = true;
direct();
}
public void buy(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true){
Scanner input = new Scanner(System.in);
for (int i = 0; i < product.length; i++){
print("Enter the amount of " + product[i].name + ": ");
product[i].setAmount(amount = input.nextInt());
buyComp = true;
}
direct();
}
}
public void listItems(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true && buyComp == false){
println("Try again: You have not bought anything");
direct();
}
for (int i = 0; i < product.length; i++){
if (product[i].amount == 0)
continue;
else println(product[i].amount + " count of " + product[i].name + " # " + product[i].price
+ " = " + (product[i].amount * product[i].price));
}
direct();
}
public void checkout(){
if (setupComp == false){
println("Shop is not setup yet!");
direct();
}
if (setupComp == true && buyComp == false){
println("Try again: You have not bought anything");
direct();
}
double subtotal = 0;
double total = 0;
double disc = 0;
for (int i = 0; i < product.length; i++){
subtotal += (product[i].amount * product[i].price);
}
if (subtotal >= discountAmt){
disc =(discount * subtotal);
total = subtotal - (disc);
}
3. These printline statements are what are running repeatedly. My method not these println statements are contained within a loop so I don't know what could be causing this issue.:
println("Thank you for coming!");
println("Sub Total: $" + subtotal);
println("-Discount: $" + (disc));
println("total\t: $" + total);
}
public void setName(String name){
this.name = name;
}
private void setPrice(double price) {
this.price = price;
}
private void setAmount(int amount) {
this.amount = amount;
}
}
Actually the if statement is an empty control flow. The checkout method is not getting called as intended by you. Please remove the first semicolon.
if (func == 4);{
checkout();
}

try catch issue Java OOP (Bank System Application)

I've fixed the duplicating error by re-writting the application in another way but now stuck on try catch to not let user enter undefended entry just letting him add the valid numbers in my switch case
import java.util.Scanner;
public class BankSystem {
private Account acc;
Scanner Input;
public BankSystem() {
this.acc = new Account(100);
Input = new Scanner(System.in);
}
public static void main(String[] args) {
BankSystem bs = new BankSystem();
bs.main();
}
public void main() {
while (true) {
try {
System.out.println("==========================");
System.out.println("========Main Menu=========");
System.out.println("Please Enter Your Choice: ");
System.out.println("1=> Main");
System.out.println("2=> New Account");
System.out.println("3=> Deposit Money");
System.out.println("4=> Withdraw Money");
System.out.println("5=> Personal Balance");
System.out.println("6=> Money Transfer");
System.out.println("7=> Full Customer Report:");
System.out.println("8=> Delete Account");
System.out.println("9=> Calculate Interest");
System.out.println("0=> Exit");
System.out.print("=> ");
int Choice = Input.nextInt();
switch (Choice) {
case 1:
main();
break;
case 2:
addAccount();
break;
case 3:
depositMoney();
break;
case 4:
withdrawMoney();
break;
case 5:
personalBalance();
break;
case 6:
transferMoney();
break;
case 7:
fullReport();
break;
case 8:
deleteAccount();
break;
case 9:
break;
case 0:
System.out
.println("Thanks For Using this App we're Looking forward to see You Again :)");
System.exit(0);
break;
default:
System.out.println("Entry is not valid.\n");
break;
}
} catch (Exception e) {
System.out.println("================================");
System.err.println("! You Have Entered Wrong Value !");
System.out.println("================================");
// break;
}
}
}
private void addAccount() {
System.out.println("Enter The Account Number:");
int acc = Input.nextInt();
System.out.println("Enter The Account First Name:");
String name = Input.next();
System.out.println("Enter The Account Last Name:");
String Sname = Input.next();
System.out.println("Enter The Amount:");
double bal = Input.nextDouble();
Customer cust = new Customer(acc, name, Sname, bal);
this.acc.insert(cust);
}
private void depositMoney() {
System.out.println("Enter Account Number:");
int acc = Input.nextInt();
System.out.println("Enter The Amount:");
double amount = Input.nextDouble();
if (amount <= 0)
System.out.println("The amount can not be negative or zero.");
else
this.acc.depositMoney(acc, amount);
}
private void withdrawMoney() {
System.out.println("Enter Account Number:");
int acc = Input.nextInt();
System.out.println("Enter The Amount:");
double amount = Input.nextDouble();
if (amount <= 0)
System.out.println("The amount can not be negative or zero.");
else
this.acc.withdrawMoney(acc, amount);
}
private void transferMoney() {
System.out.println("Enter The Sender Account Number:");
int fromAcc = Input.nextInt();
System.out.println("Enter The Receiver Account Number:");
int toAcc = Input.nextInt();
System.out.println("Enter The Amount:");
double amount = Input.nextDouble();
this.acc.transferMoney(fromAcc, toAcc, amount);
}
private void personalBalance() {
System.out.println("Enter The Account Number:");
int acc = Input.nextInt();
this.acc.personalDisplay(acc);
}
private void deleteAccount() {
System.out.println("Enter The Account Number:");
int acc = Input.nextInt();
this.acc.delete(acc);
}
private void fullReport() {
this.acc.displayList();
}
}
class Customer {
private int accNum;
private String name;
private String Sname;
private double balance;
public Customer(int a, String n, String Sn, double amount) {
accNum = a;
name = n;
Sname = Sn;
balance = amount;
}
public String getname() {
return name;
}
public String getSname() {
return Sname;
}
public int getaccNum() {
return accNum;
}
public double getBalance() {
return balance;
}
public void personalDisplay() {
System.out.println(this.getname() + " " + this.getSname()
+ "'s balance is " + this.getBalance());
}
public void deposit(double amount) {
if (amount <= 0)
System.out.println("The amount must be bigger than zero.");
else
this.balance += amount;
}
public void display() {
System.out.println(this.getaccNum() + "\t" + this.getname() + "\t"
+ this.getSname() + "\t" + this.getBalance());
}
public void withdraw(double amount) {
if (this.balance >= amount)
this.balance -= amount; // Subtract "amount" from balance
}
}
class Account {
private Customer[] Array;
private int nElem;
public Account(int max) {
Array = new Customer[max];
nElem = 0;
}
public boolean find(int data) {
int LowBoun = 0;
int HighBoun = nElem;
int Now;
while (true) {
Now = (LowBoun + HighBoun) / 2;
if (Array[Now].getaccNum() == data)
return true;
else {
if (Array[Now].getaccNum() < data)
LowBoun = Now + 1;
else
HighBoun = Now - 1;
}
if (LowBoun > HighBoun)
return false;
}
}
public void insert(Customer newData) {
int i, j;
if (!find(newData.getaccNum())) {
for (i = 0; i < nElem; i++)
if (Array[i].getaccNum() > newData.getaccNum())
break;
for (j = nElem; j > i; j--)
Array[j] = Array[j - 1];
Array[j] = newData;
nElem++;
} else
System.out.println("the number is exist!");
}
public boolean delete(int acc) {
int i;
for (i = 0; i < nElem; i++)
if (Array[i].getaccNum() == acc)
break;
if (i == nElem)
return false;
else {
for (int j = i; j < nElem; j++) {
Array[j] = Array[j + 1];
}
nElem--;
return true;
}
}
public void transferMoney(int fromAcc, int toAcc, double amount) {
int i, j;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == fromAcc)
break;
}
for (j = 0; j < nElem; j++) {
if (Array[j].getaccNum() == toAcc)
break;
}
Array[i].withdraw(amount);
Array[j].deposit(amount);
}
public void personalDisplay(int acc) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].personalDisplay();
}
public void depositMoney(int acc, double amount) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].deposit(amount);
}
public void withdrawMoney(int acc, double amount) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].withdraw(amount);
}
public void displayList() {
for (int i = 0; i < nElem; i++) {
this.Array[i].display();
}
}
}
I think you need to implement the comparable interface in the Customer class and
then do this
if(!c.contains(customer)){
c[numberOfCustomers]=customer;
numberOfCustomers++;
}
You can convert c from array to list if contains is not available on the array using Arrays.asList() method.
This might be helpful to you.
I've Solved My Code in a different way :
import java.util.*;
public class BankSystem {
private Account accArr;
Scanner Input;
public BankSystem() {
accArr = new Account(100);
Input = new Scanner(System.in);
}
public static void main(String[] args) {
BankSystem bs = new BankSystem();
bs.main();
}
public void main() {
int Choice = 1;
while (Choice != 0) {
System.out.println("==========================");
System.out.println("Please Enter Your Choice: ");
System.out.println("1=> Main");
System.out.println("2=> New Account");
System.out.println("3=> Deposit Money");
System.out.println("4=> Withdraw Money");
System.out.println("5=> Personal Balance");
System.out.println("6=> Money Transfer");
System.out.println("7=> Full Customers Report:");
System.out.println("8=> Delete Account");
System.out.println("0=> Exit");
System.out.println("==========================");
System.out.print("=> ");
try {
Choice = Input.nextInt();
} catch (InputMismatchException e) {
System.err.print("! You Have Entered Wrong Value !\n");
Input.next();
}
switch (Choice) {
case 1:
System.out.println("========Main Menu=========");
main();
break;
case 2:
System.out.println("========New Account=========");
System.out.print("Enter The Account Number:");
int acc = Input.nextInt();
System.out.print("Enter The Account First Name:");
String name = Input.next();
System.out.print("Enter The Account Last Name:");
String Sname = Input.next();
System.out.print("Enter The Amount:");
double bal = Input.nextDouble();
Customer cust = new Customer(acc, name, Sname, bal);
this.accArr.insert(cust);
break;
case 3:
System.out.println("========Deposit Money=========");
System.out.print("Enter Account Number:");
acc = Input.nextInt();
System.out.print("Enter The Amount:");
double amount = Input.nextDouble();
if (amount <= 0)
System.out
.println("The amount can not be negative or zero.");
else
this.accArr.depositMoney(acc, amount);
break;
case 4:
System.out.println("========Withdraw Money=========");
System.out.print("Enter Account Number:");
acc = Input.nextInt();
System.out.print("Enter The Amount:");
amount = Input.nextDouble();
if (amount <= 0)
System.out
.println("The amount can not be negative or zero.");
else
this.accArr.withdrawMoney(acc, amount);
break;
case 5:
System.out.println("========Personal Balance=========");
System.out.print("Enter The Account Number:");
acc = Input.nextInt();
this.accArr.personalDisplay(acc);
break;
case 6:
System.out.println("========Money Transfer=========");
System.out.print("Enter The Sender Account Number:");
int fromAcc = Input.nextInt();
System.out.print("Enter The Receiver Account Number:");
int toAcc = Input.nextInt();
System.out.print("Enter The Amount:");
amount = Input.nextDouble();
this.accArr.transferMoney(fromAcc, toAcc, amount);
break;
case 7:
System.out.println("========Full Customers Report=========");
System.out.println("Ac Num.\tName\tSurname\tBalance");
this.accArr.displayList();
break;
case 8:
System.out.println("========Delete Account=========");
System.out.print("Enter The Account Number:");
acc = Input.nextInt();
this.accArr.delete(acc);
break;
case 9:
break;
case 0:
System.out
.println("Thanks For Using this App we're Looking forward to see You Again :)");
System.exit(0);
break;
default:
System.out.println("Entry is not valid.\n");
break;
}
}
}
}
class Customer {
private int accNum;
private String name;
private String Sname;
private double balance;
public Customer(int a, String n, String Sn, double amount) {
accNum = a;
name = n;
Sname = Sn;
balance = amount;
}
public String getname() {
return name;
}
public String getSname() {
return Sname;
}
public int getaccNum() {
return accNum;
}
public double getBalance() {
return balance;
}
public void personalDisplay() {
System.out.println(getname() + " " + getSname() + "'s Balance is "
+ getBalance() + "$");
}
public void deposit(double amount) {
this.balance += amount;
System.out.println(amount + "$ has been Deposited");
}
public void withdraw(double amount) {
if (this.balance >= amount) {
this.balance -= amount;
System.out.println(amount + "$ has been Withdrawed");
} else
System.out.println("Insufficient Balance " + balance);
}
public void display() {
System.out.println(getaccNum() + "\t" + getname() + "\t" + getSname()
+ "\t" + getBalance() + "$");
}
}
class Account {
private Customer[] Array;
private int nElem;
public Account(int max) {
Array = new Customer[max];
nElem = 0;
}
public void insert(Customer newData) {
int i, j;
if (newData.getaccNum() <= 0)
System.out.println("The Account ID can't be Negative");
else
if (find(newData.getaccNum()))
System.out.println("This User is already exist!");
else {
if (newData.getBalance() < 0)
System.out.println("Amount can't be Negative!");
else {
if (nElem == (Array.length - 1))
System.out.println("Slots are Full");
else {
for (i = 0; i < nElem; i++)
if (Array[i].getaccNum() > newData.getaccNum())
break;
for (j = nElem; j > i; j--)
Array[j] = Array[j - 1];
Array[i] = newData;
nElem++;
}
}
}
}
public boolean delete(int del) {
int i;
for (i = 0; i < nElem; i++)
if (Array[i].getaccNum() == del)
break;
if (i == nElem)
return false;
else {
for (int j = i; j < nElem; j++) {
Array[j] = Array[j + 1];
}
nElem--;
System.out.println("Customer " + del + " has been Deleted !");
return true;
}
}
public boolean find(int accountId) {
if (nElem == 0) {
return false;
}
int LowBoun = 0;
int HighBoun = nElem - 1;
int now;
while (true) {
now = (LowBoun + HighBoun) / 2;
if (this.Array[now].getaccNum() == accountId)
return true;
else {
if (Array[now].getaccNum() < accountId)
LowBoun = now + 1;
else
HighBoun = now - 1;
}
if (LowBoun > HighBoun)
return false;
}
}
public void transferMoney(int fromAcc, int toAcc, double amount) {
int i, j;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == fromAcc)
break;
}
for (j = 0; j < nElem; j++) {
if (Array[j].getaccNum() == toAcc)
break;
}
Array[i].withdraw(amount);
Array[j].deposit(amount);
System.out.println(amount + "$ has been Transfered to Account Number:'"
+ toAcc + "'");
}
public void personalDisplay(int acc) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].personalDisplay();
}
public void depositMoney(int acc, double amount) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].deposit(amount);
}
public void withdrawMoney(int acc, double amount) {
int i;
for (i = 0; i < nElem; i++) {
if (Array[i].getaccNum() == acc)
break;
}
Array[i].withdraw(amount);
}
public void displayList() {
for (int i = 0; i < nElem; i++) {
this.Array[i].display();
}
}
}

show balance in simple atm in java

This code models a simple ATM machine that can deposit, withdraw, and show the 10 latest transactions in an array of 10 index values.
My problem is that I can't get the balance right after 10 deposits, the balance only seems to sum the values in my array, not including the transactions made before those ten. What am I doing wrong?
import java.util.Scanner;
public class cashier2 {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int amount = 0;
int choice = 0;
int[] transactions = new int[10];
int sum = 0;
int balance = 0;
while(choice != 4)
{
choice = menu();
switch(choice)
{
case 1:
System.out.print("deposit");
sum = keyboard.nextInt();
if(sum == 0)
{
System.out.print("wrong amount");
System.out.println();
System.out.println();
}
else
{
amount = (int) + sum;
makeTransactions(amount, transactions);
}
break;
case 2:
System.out.print("withdrawal ");
sum = keyboard.nextInt();
if(sum == 0)
{
System.out.print("wrong amount");
System.out.println();
System.out.println();
}
else
{
amount = (int) - sum;
makeTransactions(amount, transactions);
}
break;
case 3:
showTransactions(transactions, balance);
break;
case 4:
System.out.println("Exit");
break;
}
}
}
public static int menu()
{
Scanner keyboard = new Scanner(System.in);
int choice = 0;
System.out.println("Simple atm");
System.out.println();
System.out.println("1. deposit");
System.out.println("2. withdrawal");
System.out.println("3. balance");
System.out.println("4. exit");
System.out.println();
System.out.print("your choice: ");
choice = keyboard.nextInt();
return choice;
}
public static void showTransactions(int[] transactions, int balance)
{
System.out.println();
System.out.println("Tidigare transaktioner: ");
System.out.println();
for(int i = 0; i < transactions.length; i++)
{
if(transactions[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(transactions[i] + "\n");
balance = balance + transactions[i];
}
}
System.out.println();
System.out.println("Saldo: " + balance + " kr" + "\n");
System.out.println();
}
public static void makeTransactions(int amount, int[] transactions)
{
int position = findNr(transactions);
if (position == -1)
{
moveTrans(transactions);
position = findNr(transactions);
transactions[position] = amount;
}
else
{
transactions[position] = amount;
}
}
public static int findNr(int[] transactions)
{
int position = -1;
for(int i = 0; i < transactions.length; i++)
{
if (transactions[i] == 0)
{
position = i;
break;
}
}
return position;
}
//}
public static void moveTrans(int [] transactions)
{
for(int i = 0; i < transactions.length-1; i++)
{
transactions[i] = transactions[i + 1];
}
transactions[transactions.length-1] = 0;
}
}

I really need help putting in another variable (Java) For handling the bottom 3 cases:

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class CandleLine
{
public static void main(String[] args)
{
double dollars, answer;
int shipmentCode;
dollars = getPrice();
shipmentCode = getCode();
answer = getTotalPrice(dollars,shipmentCode);
output(answer,dollars);
finish();
}
public static double getPrice()
{
double price = 0.0;
boolean done = false;
while (!done)
{
String answer = JOptionPane.showInputDialog(null,"Enter the original price\n(do not use commas or dollar signs)\n or click Cancel to exit:");
if (answer == null) finish();
try
{
price = Double.parseDouble(answer);
if (price <= 0) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Your entry was not in the proper format.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
return price;
}
public static int getCode()
{
int code = 0;
boolean done = false;
while (!done)
{
try
{
String message = "Enter the shipment code:" + "\n\n1) Priority\n2) Express\n3) Standard\n\n";
code = Integer.parseInt(JOptionPane.showInputDialog(null,message));
if (code<1 || code>3) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Please enter a 1, 2, or 3.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
return code;
}
public static double getTotalPrice(double price, int shipmentcode)
{
double totalprice = 0.0;
switch(shipmentcode)
{
case 1:
totalprice = 14.95 + price;
break;
case 2:
totalprice = 11.95 + price;
break;
case 3:
totalprice = 5.95 + price;
break;
}
return totalprice;
}
public static void output(double totalprice, double price)
{
DecimalFormat twoDigits = new DecimalFormat("$#.00");
JOptionPane.showMessageDialog(null,"Your shipment fee is" + shipmentcode,"Shipment Fee",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"Your total cost is" + twoDigits.format(totalprice),"Price Total",JOptionPane.INFORMATION_MESSAGE);
}
public static void finish()
{
System.exit(0);
}
}
.
.
.
.
.
.
.
.
.
The case 3 needs to be zero when it total price exceeds $75 (no shipping cost over that price). How do I implement this?
case 3:
if (price > 75 ) {
totalPrice = price;
} else {
totalprice = 5.95 + price;
}
break;
So in total, how many possibilities are there for the shipping cost of an order?
final double [] shipmentprice = {14.95, 11.95, 5.95};
public static double getTotalPrice (final double price, final int shipmentcode)
{
return price + shipmentprice[shipmentcode -1];
}
A shorter code, but not very object oriented. I'm not sure whether I see an Enum rising. :)

Categories