Java Bank Account with arrays. Trouble with output of three accounts - java

New Class
public class NewClass {
private String accountNumber;
private String accountName;
private double balance;
public NewClass(String nameIn, String numberIn) {
accountNumber = numberIn;
accountName = nameIn;
balance = 0;
}
public String getAccountName() {
return accountName;
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amountIn) {
balance = balance + amountIn;
}
public boolean withdraw(double amountIn) {
if (amountIn < 0 && balance < 0) {
return false;
} else {
balance = balance - amountIn;
return true;
}
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
}
Main Class
public static void main(String[] args) {
String accountName = "";
String accountNum = "";
Scanner sc = new Scanner(System.in);
boolean IsAccount = false;
NewClass[] accountList = new NewClass[3];
accountList[0] = new NewClass(accountName, accountNum);
accountList[1] = new NewClass(accountName, accountNum);
accountList[2] = new NewClass(accountName, accountNum);
int i = 0;
int count = 3;
while (i < count) {
double amount;
System.out.print("Enter the account name: ");
accountName = sc.next();
accountList[i].setAccountName(accountName);
System.out.println("Enter the account number: ");
accountNum = sc.next();
accountList[i].setAccountNumber(accountNum);
System.out.print("Enter amount to deposit: ");
amount = sc.nextDouble();
accountList[i].deposit(amount);
System.out.print("Enter amount to withdraw: ");
amount = sc.nextDouble();
accountList[i].withdraw(amount);
i++;
}
while (i < count) {
System.out.println(accountList[i].getAccountNumber());
System.out.println(accountList[i].getAccountName());
System.out.println(accountList[i].getBalance());
}
}
I am new to java programming and am having trouble with my bank account program. The output is to show three accounts each containing a name, account number and balance. This i cant get to show. Any help would be greatly appreciated. Thank You.

It looks like you don't reset i back to 0 before the loop that's supposed to print the output, which means that i==count due to the previous loop, so the loop that prints the output is never entered.
Here's what you have to fix:
int i = 0; // add this
while (i < count){
System.out.println(accountList[i].getAccountNumber());
System.out.println(accountList[i].getAccountName());
System.out.println(accountList[i].getBalance());
i++; // add this too
}
Of course you can make your code more elegant with the enhanced for loop :
for (NewClass account : accountList) {
System.out.println(account.getAccountNumber());
System.out.println(account.getAccountName());
System.out.println(account.getBalance());
}

Related

How can I modify the parameter of a constructor after it has already been called?

Let's say I have this class:
public class Customer()
{
private double discountamount;
private double totalPurchase;
public Customer(double tot)
{
this.totalPurchases = tot;
if (tot > 2000.00){setDiscountAmount(0.25);}
else if (tot >= 1000.00){setDiscountAmount(0.15);}
else if (tot >= 500.00){setDiscountAmount(0.10);}
}
public double getDiscountAmount(){return discountAmount;}
public double getTotalPurchases(){return totalPurchases;}
public void setDiscountAmount(double newDiscountAmount){discountAmount = newDiscountAmount;}
public void setTotalPurchases(double newTotalPurchases){totalPurchases = newTotalPurchases;}
}
And I want to change the value of the total purchase without creating a new object.
import java.util.Scanner;
public class Discounts
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double totalPurchase;
System.out.print("Enter amount customer has spent: ");
totalPurchase = input.nextDouble();
Customer customer = new Customer(totalPurchase);
System.out.print("\nHas the customer returned with more purchases? ");
boolean loop = input.nextLine().equalsIgnoreCase("yes");
if (loop){
System.out.print("How many times? ");
int x = input.nextInt();
for (int i = 0; i < x; i++) {
// Accumulate
System.out.print("Enter amount customer has spent: ");
totalPurchase += input.nextDouble() * customer.discountAmount;
customer.setTotalPurchases(totalPurchase);
}
System.out.println("Customer Discount Amount: " + customer.discountAmount);
System.out.println("Customer Total Purchase Amount: " + customer.totalPurchases);
}
}
}
But when I print the new discount amount, it remains unchanged. So where am I going wrong and what can I do?
That's because discountAmount is only set in the constructor, which happens only once an object is instantiated. Instead, you should move the if-statement in your constructor to the setTotalPurchases, like so:
public class Customer{
private double discountamount;
private double totalPurchase;
public Customer(double tot){
this.setTotalPurchases(tot);
}
public double getDiscountAmount(){return discountAmount;}
public double getTotalPurchases(){return totalPurchases;}
public void setDiscountAmount(double newDiscountAmount){discountAmount = newDiscountAmount;}
public void setTotalPurchases(double newTotalPurchases){
totalPurchases = newTotalPurchases;
if (tot > 2000.00){
setDiscountAmount(0.25);
}else if (tot >= 1000.00){
setDiscountAmount(0.15);
}else if (tot >= 500.00){
setDiscountAmount(0.10);
}
}
}
You can move the logic for changing the discount amount to a setter:
public Customer(double tot) {
setTotalPurchases(tot);
}
public void setTotalPurchases(double newTotalPurchases){
totalPurchases = newTotalPurchases;
if (newTotalPurchases > 2000.00) {
setDiscountAmount(0.25);
} else if (newTotalPurchases >= 1000.00) {
setDiscountAmount(0.15);
} else if (newTotalPurchases >= 500.00) {
setDiscountAmount(0.10);
}
}

Java Inventory Project. Arrays

So I am trying to figure out how to get my code to work, but I keep on getting a nullError. Am I not storing my data correctly? Here is my code:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
}
catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
And of course, that is the driver class, here is my object:
public class ProductPart1 {
//Declares variables
private int productNumber;
private String productName;
private int productStock;
private double productPrice;
//Constructor
public ProductPart1(){
setNumber(0);
productName = "Null";
productStock = 0;
productPrice = 0.0;
}
//Overload constructor
public ProductPart1(int number, String name, int stock, double price){
productNumber = number;
productName = name;
productStock = stock;
productPrice = price;
}
//set the number of the object
public void setNumber(int newNumber){
productNumber = newNumber;
}
//set the name of the object
public void setName(String newName){
productName = newName;
}
//set the stock of an object
public void setStock(int newStock){
productStock = newStock;
}
//set the price of an object
public void setPrice(double newPrice){
productPrice = newPrice;
}
//get the number of an object
public int getNumber(){
return getNumber();
}
//get the name of an object
public String getName(){
return productName;
}
//get the stock of an object
public int getStock(){
return productStock;
}
//get the price of an object
public double getPrice(){
return productPrice;
}
//toString to bring the object together.
public String toString(){
return new String("Number: " + getNumber() + " Name: " + productName + " Price: " + productPrice + " Stock: " + productStock);
}
try this updated code:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
} catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
if(userInput.hasNext()){
line = userInput.nextLine();
} else {
break;
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
}
Your code creates an infinite loop. First you read line of product number, name, stock, and price. Then you go into a while loop, where you read this line out, but never again change the line variable, so it gets read again and again infinitely.

(Simple placement issue) How do I make my ATM program not withdraw below $0?

This is for my Java 1 final. I want it to kick back saying insufficient funds if the balance would go below $0 (and not create object Action -- which would be added to arraylist actions).
I believe I would use conditions in 2 places. One in the getDouble() method in class Account, as well as in the object Action() in the class Action. Perhaps in the main method though... I also don't exactly know what conditions I would put, and in the simplest way that won't mess up my program..
I also have a separate issue...
If I do a huge number, like 7 or 8 digits, it will return a different value, something like 200E7JK(example). I assume the double is reaching some kind of maximum. How can I fix this?
Main class:
public class ATM_Larrabee {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Action> actions = new ArrayList();
Account acc = new Account("N/A", "N/A", 0.0);
acc.displayWelcome();
acc.createUsernamePassword();
boolean options = true;
while(options){
acc.disconnect();
System.out.println("\nWhat action would you like to take?");
System.out.println("[ Account Balance: $" + Account.balance + " ]");
System.out.println("\n- Type 'deposit' to make a deposit into your account.");
System.out.println("- Type 'withdrawal' to make a withdrawal from your account.");
System.out.println("- Type 'history' to see your history of transactions.");
System.out.println("- Type 'exit' if you are finished.\n");
String input = in.nextLine();
if("exit".equals(input)){
break;
}
if("history".equals(input)){
Action actCopy = new Action("N/A", 0);
System.out.println("\nBelow is a history of all transactions made:\n");
for(int x = 0; x < actions.size(); x++){
actCopy = actions.get(x);
System.out.println(actCopy.getType() + ": $" + actCopy.getAmount());
}
}
if("deposit".equals(input) || "withdrawal".equals(input)){
double actionAmount;
actionAmount = acc.getDouble();
Action act = new Action(input, actionAmount);
actions.add(act);
System.out.println("\nAction accepted.");
}
}
System.out.println("\nYour Account Balance Is: $" + Account.balance);
System.out.println("\nThank you for using Really Boring Bank!");
}
}
Account class:
public class Account {
Scanner in = new Scanner(System.in);
static String username = "n/a";
static String password = "n/a";
static double balance = 0.0;
public Account(String u, String p, double b){
username = u;
password = p;
balance = b;
}
public void displayWelcome(){
String[] welcome = new String[3];
welcome[0] = "Welcome to Really Boring Banking!";
welcome[1] = "Hi there! Welcome to Really Boring Banking!";
welcome[2] = "Hello! Welcome to Really Boring Banking!";
Random rand = new Random();
int r = rand.nextInt(3);
if(r == 0){
System.out.println(welcome[0]);
}
if(r == 1){
System.out.println(welcome[1]);
}
if(r == 2){
System.out.println(welcome[2]);
}
}
public void createUsernamePassword(){
System.out.println("\nAs a new member, you will first need to create a username and password.");
System.out.println("\n[ Enter a username for your account: ]");
String input = in.nextLine();
setUsername(input);
System.out.println("\n[ Enter a password for your account: ]");
input = in.nextLine();
setPassword(input);
}
public void disconnect(){
Random rand = new Random();
int r = rand.nextInt(5);
if(r == 1){
System.out.println("\n[ Connection to server lost. Please log back into your account. ]");
boolean loggedIn = false;
boolean correctUsername = false;
boolean correctPassword = false;
while(!loggedIn){
while(!correctUsername){
System.out.println("\n[ Enter username: ]");
String input = in.nextLine();
if(Account.username.equals(input)){
correctUsername = true;
System.out.println("\nUsername Accepted");
}
else{
System.out.println("[ Incorrect username. Please try again. ] ");
}
}
while(!correctPassword){
System.out.println("\n[ Enter password: ]");
String input = in.nextLine();
if(Account.password.equals(input)){
correctPassword = true;
System.out.println("\nPassword Accepted");
loggedIn = true;
System.out.println("\nSuccessfully logged back into account: "+ Account.username + ".");
}
else{
System.out.println("[ Incorrect password. Please try again. ] ");
}
}
}
}
}
public double getDouble(){
boolean validInput = false;
double doub = 0.0;
while (!validInput) {
System.out.println("\n[ Please enter an amount: ]\n");
String input = in.nextLine();
try {
doub = Double.parseDouble(input);
validInput = true;
} catch (NumberFormatException e) {
validInput = false;
}
}
return doub;
}
public String getUsername(){
return Account.username;
}
public void setUsername(String u){
username = u;
}
public String getPassword(){
return Account.password;
}
public void setPassword(String p){
password = p;
}
public double getBalance(){
return Account.balance;
}
public void setSeed(double b){
balance = b;
}
}
Action class:
public class Action {
double amount = 0;
String type;
// object for withdrawals and deposits (saved into an arraylist elsewhere)
public Action(String t, double a){
type = t;
amount = a;
if("deposit".equals(type)){
type = "deposit";
Account.balance = Account.balance + a;
}
if("withdrawal".equals(type)){
type = "withdrawal";
Account.balance = Account.balance - a;
}
}
// gets and sets
public String getType(){
return this.type;
}
public void setType(String t){
type = t;
}
public double getAmount(){
return this.amount;
}
public void setAmount(double a){
amount = a;
}
}
Making balance (and the other fields) static in Account makes everything a global (and means you can only have one Account). But, in the context of your question,
Account.balance = Account.balance - a;
needs a test to make sure a isn't greater than the Account.balance like
if (Account.balance >= a) {
// Account.balance = Account.balance - a;
Account.balance -= a;
} else {
System.err.printf("%d is greater than %d and would be an overdraft%n",
a, Account.balance);
}
in the long term though you'll need instance(s) of Account (so make them instance fields and create an instance of Account).

Skipping over while statement

I was having some trouble with a program where I am suppose to allow a user to enter any amount of numbers into a program until they do not want to anymore. The program then should calculate the average and maximum of the numbers inputed. Where did I go wrong?
import java.util.Scanner;
public class DataSet
{
//Instance Variables
private double newValue;
private double sum;
private int count;
Scanner scan = new Scanner(System.in);
//Constructors
public DataSet()
{
double newValue = 0;
double sum = 0;
int count = 0;
}
public void run()
{
}
public double getaddValueToSet()
{
System.out.println("Please enter a number");
newValue = scan.nextDouble();
count += 1;
return newValue;
}
public double getSum()
{
sum += newValue;
return sum;
}
public double getAverage()
{
double average;
average = sum/count;
return average;
}
public double getMaximum()
{
double max=newValue;
if(newValue >= max)
{
max = newValue;
}
return max;
}
public String toString()
{
String str;
str = "Average: " + getAverage() + "\n" +
"Maximum: " + getMaximum();
return str;
}
}
import java.util.Scanner;
public class DataSetRunner
{
public static void main(String [] args)
{
String answer = "yes";
Scanner scan = new Scanner(System.in);
{
System.out.println("Do you want to enter another number?");
answer = scan.next();
}
while(answer.equals("yes"))
{
DataSet d1 = new DataSet();
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
}
}
}
DataSet d1 = new DataSet();
do {
System.out.println("Do you want to enter another number?");
answer = scan.next();
if (answer.equalsIgnoreCase("YES")) {
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
} else {
break;
}
} while (true);

binarySearch errors in Java

I have a BankAccount class that models bank account information and a main method that is supposed to create an array list of BankAccount objects from user input and then write that info to a text file.
Here's my BankAccount class:
package BankAccount;
public class BankAccount implements Comparable<BankAccount> {
String accountNumber;
String firstName, lastName;
char middleInitial;
double balance;
public static double OVERDRAFT_FEE = 26.00;
public BankAccount(String acno, String fName, char midInit, String lName, double initBal){
acno = accountNumber;
fName = firstName;
midInit = middleInitial;
lName = lastName;
initBal = balance;
}
public String getAccountNumber(){
return accountNumber;
}
public String getFirstName(){
return firstName;
}
public char getMiddleInitial(){
return middleInitial;
}
public String getLastName(){
return lastName;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
if (amount > 0)
balance = balance + amount;
else
throw new IllegalArgumentException("deposit(double amount): Amount cannot be less than 0.");
}
public void withdraw(double amount){
if (balance >= amount && amount > 0)
balance = balance - amount;
else if(balance < amount && amount > 0)
balance = balance - amount - OVERDRAFT_FEE;
else
throw new IllegalArgumentException("withdraw(double amount): Amount cannot be less than 0.");
}
#Override
public int compareTo(BankAccount another){
if (Integer.parseInt(this.getAccountNumber()) > Integer.parseInt(another.getAccountNumber()))
return 1;
else if(Integer.parseInt(this.getAccountNumber()) < Integer.parseInt(another.getAccountNumber()))
return -1;
else
return 0;
}
}
My main method looks like this:
public class GeauxBank
{
public static void main(String[] args)
{
ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
Scanner keyb = new Scanner(System.in);
// write code to read data from acinfo.dbf. Be sure to handle
// FileNotFoundException in a try-catch statement. You don't
// need to do anything in the catch block.
int option;
String acno;
String fName;
char midInit;
String lName;
double initBal=0,amount;
int pos;
do
{
menu();
System.out.println();
System.out.print("Select an option->");
option = keyb.nextInt();
System.out.println();
switch(option)
{
case 1:
System.out.print("Enter a 10-character long account number->");
acno = keyb.next();
System.out.print("Customer's first name ->");
fName = keyb.next();
System.out.print("Customer's middle initial ->");
midInit = keyb.next().charAt(0);
System.out.print("Customer's last name ->");
lName = keyb.next();
System.out.print("Initial Deposit ->");
initBal = keyb.nextDouble();
Collections.sort(accounts);
pos = binarySearch(accounts,acno);
if (pos < 0)
{
try
{
accounts.add(new BankAccount(acno,fName,midInit,lName,initBal));
Collections.sort(accounts);
}
catch(IllegalArgumentException e)
{
System.out.println(e);
}
}
else
System.out.println(acno+" has already being asssigned another customer");
break;
case 2:
System.out.println("Enter the 10-character long account number of the account you wish to close->");
acno = keyb.next();
pos = binarySearch(accounts, acno);
accounts.remove(pos);
break;
case 3:
System.out.println("Enter the 10-character long account number->");
acno = keyb.next();
System.out.println("Enter the amount you wish to deposit->");
amount = keyb.nextDouble();
pos = binarySearch(accounts, acno);
accounts.get(pos).deposit(amount);
break;
case 4:
System.out.println("Enter the 10-character long account number->");
acno = keyb.next();
System.out.println("Enter the amount you wish to withdraw->");
amount = keyb.nextDouble();
accounts.get(binarySearch(accounts, acno)).withdraw(amount);
break;
case 5:
System.out.println("Enter the 10-character long account number->");
acno = keyb.next();
accounts.get(binarySearch(accounts, acno)).getBalance();
break;
case 6:
int i;
int length = accounts.size();
for(i = 0; i < length; i++) {
System.out.print(accounts.get(i).getFirstName()+" ");
System.out.print(accounts.get(i).getMiddleInitial()+" ");
System.out.println(accounts.get(i).getLastName());
}
break;
case 0:
break;
default:
System.out.println("Invalid menu option");
}
}while (option != 0);
try{
PrintWriter writer = new PrintWriter("acinfo.dbf");
int i;
int length = accounts.size();
for(i = 0; i < length; i++){
writer.write(accounts.get(i)+"");
}
writer.close();
}
catch(FileNotFoundException f) {
System.out.println("The file acinfo.dbf does not exist.");
}
}
/**
* displays a text-based menu interface for this application
*/
public static void menu()
{
System.out.println();
System.out.println("G E A U X B A N K L O U I S I A N A L T D.");
System.out.println("=================================================");
System.out.println("[1]...............................open an account");
System.out.println("[2]..............................close an account");
System.out.println("[3].......................................deposit");
System.out.println("[4]....................................withdrawal");
System.out.println("[5]...............................balance inquiry");
System.out.println("[6].............................customers listing");
System.out.println("[0]..........................................exit");
System.out.println("=================================================");
}
/**
* searches an array list of BankAccount objects for a matching
* account number using the Binary Search algorithm.
* #param accounts an array list of BankAccount objects
* #param acno a string
* #return the index of the BankAccount object in the array list or
* with the account number that is the same as acno if such a BankAccount
* object can be found in the accounts array list; otherwise, the negative
* of the position the BankAccount object whose account number would
* have matched acno had it been found.
*/
public static int binarySearch(ArrayList<BankAccount> accounts, String acno)
{
int i;
int low,mid=0,high;
low = 0;
high = accounts.size()-1;
while (low <= high)
{
mid = (low+high)/2;
if (acno.compareTo(accounts.get(mid).getAccountNumber())==0)
return mid;
else if (acno.compareTo(accounts.get(mid).getAccountNumber())< 0)
high = mid-1;
else
low = mid+1;
}
return -1-mid;
}
}
I'm having problems with the binarySearch method. I can create one bank account just fine but when I try to create a second one, I get this message:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1167)
at geauxbank.GeauxBank.binarySearch(GeauxBank.java:172)
at geauxbank.GeauxBank.main(GeauxBank.java:57)
Java Result: 1
It also gives me a similar message any time I try to use any other case in the switch statement that uses the binarySearch method. I don't know why this is. Also, when I try to write the information to a text file, I get this in the text file: BankAccount.BankAccount#1b67f74
or this: null null
I really don't know what is causing these problems. Any insight and clarity would be appreciated.
Your assignments are the wrong way around.
This takes the parameter and overwrites it with the fields which is null. The fields is left as null and you get an NPE when you attempt to dereference it.
acno = accountNumber;
try
accountNumber = acno;
I suggest you make fields final (unless you need to be able to change them) and you won't have this problem.

Categories