having trouble with my output. It prints in the correct format as long as the last digit isn't a zero. In other words, it will output $1.75 but for $1.50 I get $1.5. I know the "%.2f" is supposed to format it but I can't figure out where to put it in my code. Thanks!
/**
This Class is designed to work with an application program for a Vending Machine.
*/
public class VendingMachine
{
private double money;
private double amountDue;
private double change;
private String selection;
/**
Constructor for the Class.
*/
public VendingMachine()
{
money = 0.00;
amountDue = 0.00;
change = 0.00;
selection = "";
}
/**
Explicit Constructor for the class that gives variables more specific values.
*/
public VendingMachine(double money, double change, double amountDue, String selection)
{
this.money = money;
this.amountDue = amountDue;
this.change = change;
this.selection = selection;
}
/**
Accesssor method for the selection.
#return the selection of the user.
*/
public String getSelection()
{
return selection;
}
/**
Accessor method to get the amount of money the user puts in the machine.
#return the amount of money.
*/
public double getMoney()
{
return money;
}
/**
Accessor method for the amount due.
#return the amount due.
*/
public double getAmountDue()
{
return amountDue;
}
/**
Accessor method for getting the user's change.
#return the user's change.
*/
public double getChange()
{
return change;
}
/**
Mutator method for the selection.
#param the selection of the user.
*/
public void setSelection(String selection)
{
this.selection = selection;
}
/**
Mutator method for money.
#param the money put into machine.
*/
public void setMoney(double money)
{
this.money = money;
}
/**
Mutator method for amount due.
#param the selection of the user.
*/
public double setAmountDue(String selection)
{
if (selection.equals("A1") || selection.equals("A2") || selection.equals("A3"))
{
amountDue = 1.25;
}
else if (selection.equals("B1") || selection.equals("B2") || selection.equals("B3"))
{
amountDue = 1.00;
}
else if (selection.equals("C1") || selection.equals("C2") || selection.equals("C3"))
{
amountDue = 1.50;
}
return amountDue;
}
/**
Mutator method for the change.
#param the money put into machine.
*/
public void setChange(double money)
{
change = money - amountDue;
this.change = change;
}
/**
Method for converting all variables into a String statement.
#return a String of the total transaction.
*/
public String toString()
{
return ("Your selection: " + selection + "\nYour amount due: " + amountDue + "\nYour change: " + change);
}
}
import java.util.*;
/**
This program runs a Vending Machine and interacts with the user.
*/
public class VendingMachineTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String input;
String[] choices = {"A1~~SNICKERS~~~~~~~~$1.25", "A2~~MILKY WAY~~~~~~~$1.25" , "A3~~TWIX~~~~~~~~~~~~$1.25",
"B1~~ORIGINAL CHIPS~~$1.00", "B2~~BBQ CHIPS~~~~~~~$1.00" , "B3~~PRETZELS~~~~~~~~$1.00",
"C1~~COKE~~~~~~~~~~~~$1.50", "C2~~SPRITE~~~~~~~~~~$1.50", "C3~~DR. PEPPER~~~~~~$1.50",
};
displayItems(choices);
VendingMachine user = new VendingMachine();
do
{
System.out.print("Please make your selection: ");
input = in.nextLine();
}
while (!(input.equals("A1") || input.equals("A2") || input.equals("A3") ||
(input.equals("B1") || input.equals("B2") || input.equals("B3") ||
(input.equals("C1") || input.equals("C2") || input.equals("C3")))));
user.setSelection(input);
user.setAmountDue(input);
System.out.print("Enter the amount you put in the machine: ");
double amount = in.nextDouble();
user.setMoney(amount);
user.setChange(amount);
System.out.println(user);
System.out.print("Thank You for your purchase!");
}
/**
A method for displaying all of the options in the machine.
#param an array of choices
#return an array of choices.
*/
public static void displayItems(String[] choices)
{
for (int i = 0; i < choices.length; i++)
{
System.out.print(choices[i]);
System.out.println();
}
return;
}
}
This should do the trick:
public String toString() {
return String.format( "Your selection: %s: \nYour amount due: %.2f \nYour change: %.2f",
selection,
amountDue,
change);
}
Related
I've been assigned to make a program from CS class to edit a previous program and include exceptions and such, and also serialize and de-serialize a file for its data. The program seems to work fine when it comes to depositing money, HOWEVER when I try to withdraw money, it just straight up doesn't work. And I'm not sure why even after going back through my other classes and tracing it to the source.
Here's my code.
import java.io.Serializable;
/**
The BankAccount class is an abstract class that holds
general information about a bank account. Classes
representing specific types of bank accounts should inherit
from this class.
*/
public abstract class BankAccount implements Serializable
{
private double balance;
private double interestRate; //annual interest rate
private double serviceCharges;
private int numDeposits;
private int numWithdrawals;
public BankAccount() {
}
public BankAccount(double bal, double rate)
{
try {
deposit(bal);
} catch (InvalidDeposit e) {
System.out.println(e.getMessage());
balance = 0;
}
interestRate = rate;
rate = 0.0;
numDeposits = 0;
numWithdrawals = 0;
}
/**
This constructor sets the bank account's
balance, interest rate, and service charges.
#param bal Sets the bank account's balance
#param rate Sets the bank account's interest rate
*/
public BankAccount(double bal, double rate, double charges)
{
try {
deposit(bal);
} catch (InvalidDeposit e) {
System.out.println(e.getMessage());
balance = 0;
}
interestRate = rate;
rate = 0.0;
serviceCharges = charges;
charges = 0.0;
numDeposits = 0;
numWithdrawals = 0;
}
/**
The setRate() method will set the interest
rate for the bank account.
#param rate Sets the interest rate for the account
*/
public void setRate(double rate)
{
interestRate = rate;
}
/**
The setCharges() method will set the value of
any service charges.
#param charges Sets the amount of service charges
*/
public void setCharges(double charges)
{
serviceCharges = charges;
}
/**
The getBalance() method will return the
bank account's balance when called.
#return balance Returns the bank account balance
*/
public double getBalance()
{
return balance;
}
/**
The getRate() method will return the
bank account's interest rate when called.
#return interestRate Returns the account interest rate
*/
public double getRate()
{
return interestRate;
}
/**
The getCharges() method will return the
bank account's service charge amount.
#return serviceCharges Returns the service charge amount
*/
public double getCharges()
{
return serviceCharges;
}
/**
The getNumDeposits() method pulls the number
of deposits totaled in the deposit method and
returns the integer value.
#return numD Returns the total number of deposits made
*/
public int getNumDeposits()
{
return numDeposits;
}
/**
The deposit() method accepts an entered deposit
amount and adds it to the balance. It also totals
how many deposits are made.
#return balance Returns the new balance amount
after deposits have been made.
#exception InvalidDeposit When an invalid deposit is given.
*/
public void deposit(double amtD) throws InvalidDeposit
{
if (amtD <= 0 || amtD > 10000)
throw new InvalidDeposit(amtD);
else
{
balance = balance + amtD;
numDeposits++;
}
}
/**
The getNumWithdrawal() method pulls the number
of withdrawals totaled in the withdraw method and
returns the integer value.
#return numWithdrawals Returns the total number of withdrawals made
*/
public int getNumWithdrawals()
{
return numWithdrawals;
}
/**
The withdraw() method accepts an entered withdrawal amount
and subtracts it from the balance. It also keeps a running
total of how many withdrawals are made.
#return balance Returns the new account balance after
withdrawals have been made.
#exception InvalidWithdrawal When an invalid withdrawal is attempted
*/
public void withdraw(double amtW) throws InvalidWithdrawal
{
if (amtW <= 0 || amtW > 10000 || amtW > balance)
throw new InvalidWithdrawal(amtW);
else
{
balance = balance - amtW;
numWithdrawals++;
}
}
/**
The calcInterest() method calculates the interest
amount earned each month and adds it to the balance.
#return balance The new balance is returned after
the interest amount has be calculated and added to it.
*/
public void calcInterest()
{
double monthlyIR, monthlyI;
monthlyIR = interestRate / 12;
monthlyI = balance * monthlyIR;
balance += monthlyI;
}
/**
The monthlyProcess() method will calculate the balance
after subtracting the amount of service charges.
#return balance Returns the balance amount after
service charges have been subtracted.
*/
public void monthlyProcess()
{
balance -= getCharges();
calcInterest();
numDeposits = 0;
numWithdrawals = 0;
}
} //end BankAccount class
import java.io.Serializable;
/**
This class holds the data for a savings account.
*/
public class SavingsAccount extends BankAccount implements Serializable
{
public final static double INACTIVE_AMT = 25.00;
private boolean status;
public SavingsAccount()
{
}
/**
This Constructor sets the account balance and
interest rate for the savings account.
#param acctBal Sets the account balance
#param interest Sets the account interest rate
*/
public SavingsAccount(double acctBal, double interest)
{
super(acctBal, interest);
acctBal = super.getBalance();
}
/**
This Constructor sets the account balance and
interest rate for the savings account.
#param acctBal Sets the account balance
#param interest Sets the account interest rate
*/
public SavingsAccount(double acctBal, double interest, double acctCharges)
{
super(acctBal, interest, acctCharges);
acctBal = super.getBalance();
}
/**
The getStatus() method will return true or
false for the activity status of the savings account.
#return status Returns the status of the savings account
*/
public boolean getStatus()
{
return status;
}
/**
The checkStatus() method checks to see if the
account balance is more or less than $25. If more than,
the account is active. If less than, the account is in active.
#return status Returns the activity status for the account.
*/
public boolean checkStatus() //
{
status = false;
if (getBalance() >= INACTIVE_AMT)
{
status = true;
}
return status;
}
/**
The withdraw() method checks the account status and
returns the account balance after a withdrawal.
#param acctBal Sets the account balance
#param amtWD Sets the withdrawal amount
#return super.withdraw(amtWD) returns the account
a balance after the calculations done in the superclass.
#exception InvalidDeposit When an invalid deposit is given.
*/
public void withdraw(double amtWD) throws InvalidWithdrawal
{
if (checkStatus() == true)
super.withdraw(amtWD);
checkStatus();
if (checkStatus() == false)
System.out.println("The withdrawal can't be made. The account is inacitve.");
}
/**
The deposit() method checks the account status and
returns the account balance after a deposit.
#param acctBal Sets the account balance
#param amtD Sets the deposit amount
#return super.deposit(amtD) returns the account
a balance after the calculations done in the superclass.
#exception InvalidWithdrawal When an invalid withdrawal is attempted.
*/
public void deposit(double amtD) throws InvalidDeposit
{
if ((getStatus() == false) && (getBalance() + amtD > INACTIVE_AMT))
super.deposit(amtD);
}
public void monthlyProcess()
{
double accountCharges = 0.0;
if (super.getNumWithdrawals() > 4)
accountCharges = ((getNumWithdrawals() - 4) * 1) + super.getCharges();
else
accountCharges = 0 + super.getCharges();
super.setCharges(accountCharges);
super.monthlyProcess();
checkStatus();
if (checkStatus() == false)
System.out.println("The balance is less $25. The account is inactive.");
}
/**
toString method
#return A string representation of an object.
*/
public String toString()
{
String str1 = "The account is inactive!";
String str2 = "The account is active.";
String msg = " ";
msg = "Balance: " + getBalance() + "\tRate: " + getRate()
+
"\tCharges: " + getCharges() + "\tNo. of Deposits: " + getNumDeposits() +
"\tNo. of Withdrawals: " + getNumWithdrawals() + "\nStatus: ";
if (super.getBalance() < INACTIVE_AMT)
msg += str1;
else
msg += str2;
return msg;
}
} //end SavingsAccount class
/**
InvalidDeposit will extend the Exception
class and allow the program to throw invalid
data.
*/
public class InvalidDeposit extends Exception {
//No arg constructor
public InvalidDeposit() {
super("Cannot deposit amounts less than or equal to $0 or greater than $10,000.");
}
/**
This constructor reports the attempted deposit amount.
#param amtD The amount to be deposited
*/
public InvalidDeposit(double amtD) {
super("Error: amount to deposit should be > 0 and < 10,000. ");
}
}
/**
InvalidWithdrawal will extend the Exception class
and allow the program to throw invalid data.
*/
class InvalidWithdrawal extends Exception
{
//no arg constructor
public InvalidWithdrawal()
{
super("Cannot withdraw ammounts less than or equal to 0, " +
"amounts greater than the current balance, or amounts greater than $10,000.");
}
/**
The constructor reports the attempted withdrawal amount.
#param amtWD The amount intended to be withdrawn
*/
public InvalidWithdrawal(double amtWD)
{
super("Error: there is not enough money to withdraw.");
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
/**
The following application will demonstrate the
exceptions and service classes stated above.
*/
public class SavingsDemo
{
private static String filename = "savingsAccount.dat"; //name of the file where the object will be serialized
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int choice = 0;
double amt, rate, charge;
System.out.print("Please enter the initial balance: ");
amt = keyboard.nextDouble();
while (amt < 0 || amt > 10000) {
try {
amt = keyboard.nextDouble();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.print("Please re-enter: ");
amt = keyboard.nextDouble();
}
}
System.out.println("Please enter interest rate: ");
rate = keyboard.nextDouble();
System.out.println("Please enter monthly charge: ");
charge = keyboard.nextDouble();
SavingsAccount acct1 = new SavingsAccount(amt, rate, charge);
while (choice != 4) {
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. View account");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = keyboard.nextInt();
switch (choice)
{
case 1:
System.out.print("Enter deposit amount: ");
amt = keyboard.nextDouble();
boolean done1 = true;
while (amt <= 0 || amt > 10000) {
try {
acct1.deposit(amt);
} catch (InvalidDeposit e) {
System.out.println(e.getMessage());
System.out.println("Please re-enter: ");
amt = keyboard.nextDouble();
}
}
break;
case 2:
System.out.print("Enter withdrawal amount: ");
amt = keyboard.nextDouble();
while (amt <= 0 || amt > acct1.getBalance() || amt > 10000) {
try {
acct1.withdraw(amt);
} catch (InvalidWithdrawal e) {
System.out.println(e.getMessage());
System.out.println("Please re-enter: ");
amt = keyboard.nextDouble();
}
}
break;
case 3:
System.out.println(acct1);
break;
case 4:
break;
default:
System.out.println("Invalid menu choice!");
}
}
System.out.println("\n\nBefore monthly process.... \n" + acct1);
System.out.println("Performing monthly process...");
acct1.monthlyProcess();
System.out.println("\n\nAfter monthly process.... \n" + acct1);
try {
System.out.println("\nSerializing object to file " + filename);
writeObj(acct1);
System.out.println("\nDeSerializing object from file " + filename);
acct1 = readObj();
System.out.println("\nDeSerialized object details are ");
System.out.println(acct1);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private static void writeObj(SavingsAccount acc) throws IOException
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(acc);
oos.close();
}
private static SavingsAccount readObj() throws IOException
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
SavingsAccount acc = null;
try {
acc = (SavingsAccount)(ois.readObject());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
ois.close();
return acc;
}
}
I understand it might be hard to go through since it's lengthy, but what you're looking for is the "withdraw" method in the BankAccount and SavingsAccount classes. In my SavingsDemo class it should be removing money from the balance if it meets certain parameters, but even when it does meet those special rules, it won't remove money from the account.
Hey guys I have been working on this program for class the past couple hours and just cant seem to get these last 2 issues resolved. Its basically a slightly modified CashRegister class with basic functions through a menu. The problems I am having are:
1) After the user makes a menu selection for the first time, every subsequent time the menu shows up in console twice and I cant seem to find a fix for this.
2) Also whenever I choose to display the content of my CashRegister, the first line is always output as 0.00 no matter the input.
Here is my CashRegister class followed by my tester:
import java.util.ArrayList;
/**
*
*/
/**
* #author Cole
*
*/
public class CashRegister {
private double dailyTotal;
private double totalPrice;
ArrayList<Double> items;
/**
Constructs a cash register with cleared item count and total.
*/
public CashRegister()
{
items = new ArrayList<Double>();
dailyTotal = 0;
totalPrice= 0;
}
/**
Adds an item to this cash register.
#param price the price of this item
*/
public void addItem(double price)
{
items.add(price);
dailyTotal = dailyTotal + price;
}
/**
Gets the price of all items in the current sale.
#return the total amount
*/
public double getTotal()
{
for(int x=0; x<items.size(); x++){
totalPrice = totalPrice + items.get(x);
}
return totalPrice;
}
/**
Gets the number of items in the current sale.
#return the item count
*/
public int getCount()
{
return items.size();
}
/**
Clears the item count and the total.
*/
public void clear()
{
items.clear();
totalPrice = 0;
}
public void display(){
for(int x=0; x<items.size(); x++){
System.out.printf("%10.2f%n", items.get(x));
}
System.out.println("------------------------------");
}
public double getDailyTotal(){
dailyTotal = dailyTotal + totalPrice;
return dailyTotal;
}
}
import java.util.ArrayList;
import java.util.Scanner;
/**
*
*/
/**
* #author Cole
*
*/
public class Prog2 {
/**
* #param args
*/
public static final String MENU = "******************************************\n" +
"* Enter \"n\" to start a new Cash Register. *\n" +
"* Enter \"a\" to add an item to the current Cash Register. *\n" +
"* Enter \"d\" to display the total of the current Cash Register. *\n" +
"* Enter \"e\" to exit the program. *\n" +
"******************************************";
public static final String NEW_CUSTOMER = "n";
public static final String ADD_ITEM = "a";
public static final String DISPLAY = "d";
public static final String EXIT = "e";
public static void main(String[] args) {
// TODO Auto-generated method stub
CashRegister register = new CashRegister();
Scanner keyboard = new Scanner(System.in);
String input;
double userInput = 0;
do {
input = printMenu(keyboard);
if(input.equals(NEW_CUSTOMER)){
register.getDailyTotal();
register.clear();
}
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
register.addItem(userInput);
userInput = keyboard.nextDouble();
}
else if(input.equalsIgnoreCase(DISPLAY)){
register.display();
System.out.println("Total: " + register.getTotal());
System.out.println("Item Count: " +register.getCount());
}
else if(input.equalsIgnoreCase(EXIT)){
System.out.printf("Daily Sales Total: " + "%.2f%n",register.getDailyTotal());
System.out.println("Program Ended...");
break;
}
}while(input != EXIT);
}
public static String printMenu(Scanner input){ //this method displays the menu for the user
String response = "no reponse yet";
System.out.println(MENU);
response = input.nextLine();
return response; //response returned based on the users input
}
}
You need to get input from the user before you add the item, that's why you are getting a 0 for your first item. Since your value for userInput is set to 0 at the beginning and your statements are switched you will always initialy create an item with 0.0 for it's value and all the other values will be one step behind the actual inputs.
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
userInput = keyboard.nextDouble();
register.addItem(userInput);
}
I want to read data from a text file and print the output to both the terminal and a text file. I have a loop that reads for numbers and one that reads for non-numerical characters, but nothing is printing out to the terminal. i am new to programming.
I am transforming an old project to a new one by the way.
package studenttester;
public class Student
{
private String name;
double quizScore;
double quizAverage;
private int numQuizzes;
String grade;
/**
* Returns the name of a student
*
* #return the name of the student
*/
public Student (String inName)
{
name = inName;
quizAverage = 0;
quizScore = 0;
numQuizzes = 0;
}
public String getName()
{
return name;
}
/**
* Adds a quiz score to the total quiz score of the student
*
* #param score the score of a quiz
*/
void addQuiz(int score)
{
numQuizzes += 1;
quizScore += score;
}
/**
* Returns the total score of all the quizzes combined that student took
*
* #return the value of score
*/
double getTotalScore()
{
return quizScore;
}
/**
* Returns the average score of all the quizzes a student took
*
* #return
*/
double getAverageScore()
{
return quizScore / numQuizzes;
}
}
package studenttester;
import java.io.*;
import java.util.Scanner;
public class StudentTester {
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Student Name Number of Quizzes Average");
Scanner reader = new Scanner(new File("quizScores.txt"));
String studentName = "", first="", last="";
while (!reader.hasNext("-10"))
{
}
while (reader.hasNextDouble())
{
first = first+reader.next();
studentName = last + first;
}
Student newStudent = new Student(studentName);
while (reader.hasNextDouble() && !reader.hasNext("-10"))
{
System.out.printf("");
}
{
// writer.close;
}
}
}
The "red underline" means an compiler error, I guess.
Have a look to your while loop, it seems to be wrong.
Try ...
while (reader.hasNextDouble() && (!reader.hasNext("-10")))
System.out.printf("");
}
reader.close();
instead.
I'm having a little bit of trouble with my code that I can't seem to figure out. Whenever I run this, it prints "Customer is null" instead of inserting their name. It also always calculates all tax as 0 (something wrong with my if statement?).
Is there any chance you guys can spot the issue? It seems as though everything else works correctly. (Wrote methods in Customer class, calling them in TestCustomer class, and the instructions are at the end of the post).
Thank you for anyone who takes the time to read this and attempt to help. Sorry for so much information, I just have no clue what is causing this, so I figured I'd include everything.
Customer class
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Customer {
public static double taxRate = 0.00;
public static double saleRate = 0.00;
String customerName;
double listSaleAmount;
double saleDiscount = 0;
double netSaleAmount;
double taxAmount;
double saleTotal;
boolean taxable;
public double total;
public Customer (String customerName, boolean taxable) {
}
public void calculateTax () {
saleDiscount = listSaleAmount*(saleRate/100);
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable = true){
taxAmount = netSaleAmount*(taxRate/100);
}
else{
taxAmount = 0;
}
saleTotal = netSaleAmount + taxAmount;
total += saleTotal;
}
public void printRecord () {
System.out.println("Customer is " + customerName);
System.out.println("Sale amount is $" + listSaleAmount);
System.out.println("Discount amount is $" + saleDiscount);
System.out.println("Net Sale Amount is $" + netSaleAmount);
System.out.println("Tax amount is $" + taxAmount);
System.out.println("Total Sale Amount is $" + saleTotal);
System.out.println(" ");
}
public static void changeTaxAmount () {
Scanner input = new Scanner(System.in);
double userTaxAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Tax Rate? (8.25 & 8.50 for testing)"));
taxRate = userTaxAmount;
}
public static void changeSaleRate () {
Scanner input = new Scanner(System.in);
double userSaleAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Sale Discount Rate? (0.00 & 7.50 for testing)"));
saleRate= userSaleAmount;
}
public static void printTaxRate() {
System.out.println("Tax Rate is " + taxRate + "%.");
}
public static void printSaleRate() {
System.out.println("The Sale Rate is " + saleRate + ".");
System.out.println(" ");
}
}
TestCustomer class
public class TestCustomer {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer1 = new Customer("Annie Smith", true);
Customer customer2 = new Customer("Bob Wilson", false);
Customer.changeTaxAmount();
Customer.printTaxRate();
Customer.changeSaleRate();
Customer.printSaleRate();
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
customer1.calculateTax();
customer1.printRecord();
customer2.calculateTax();
customer2.printRecord();
Customer.changeTaxAmount();
Customer.printTaxRate();
Customer.changeSaleRate();
Customer.printSaleRate();
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
customer1.calculateTax();
customer1.printRecord();
customer2.calculateTax();
customer2.printRecord();
double total2 = customer1.total + customer2.total;
System.out.println("The total of all sales is $" + total2);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
Also, thank you to those of you who helped me with my last question on this project. You helped a lot.
In your constructor
public Customer (String customerName, boolean taxable) {
}
You are passed in parameters, but you never assign them to your class fields.
try
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
You have to define your constructor in customer class to set values of customerName and texable class level variables:
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
Also, there seems to be problem with the below if condition:
if (taxable = true){
You should use == operator for comparing:
if (taxable == true) {
Actually, you don't need to compare it. Just use:
if (taxable) {
Your constructor in Customer class should assign the name and taxable value to Customer data member.
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
Instead of using if (taxable = true), simply use if (taxable).
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So I am still fairly new to java. I have written this but am not sure as to why when I run it, the amounts will not add to what is set in the client.
For example: I enter 500 as starting balance, if I hit deposit, and type 500, and then hit case 3, it should say 1000 but it still says 500. And then If i hit withdraw, it says I have -500.
Any ideas? Thanks
package bankaccount;
import java.util.Random;
import java.util.Scanner;
public class Client {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String cusName = input.nextLine();
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100000);
System.out.println("Enter Initial Balance: ");
int balance = input.nextInt();
BankAccount b1 = new BankAccount(cusName, accNo, balance);
int menu;
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
do {
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
System.out.print("Enter depost amount:");
Money.amount = input.nextInt();
b1.getDeposit();
break;
case 2:
System.out.println("Current Account Balance=" + b1.getBalance());
System.out.print("Enter withdrawal amount:");
Money.amount = input.nextInt();
b1.getWithdraw();
break;
case 3:
b1.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
public class Money
{
public static int accountNumber, balance=0;
static int amount;
static String name;
public void setDeposit(int amount) {
balance = balance + amount;
}
public int getDeposit()
{
balance = balance + amount;
if (amount < 0) {
System.out.println("Invalid");
}
return 1;
}
public void setBalance(int b)
{
b = balance;
}
public int getBalance()
{
return balance;
}
public void setWithdraw(int amount) {
balance = balance - amount;
}
public int getWithdraw()
{
balance = balance - amount;
if (balance < amount)
{
System.out.println("Not enough funds.");
return 1;
}
else if (amount < 0) {
System.out.println("Invalid");
return 1;}
else
return 0;
}
import java.util.*;
public class BankAccount extends Money {
static String name;
public static int balance, amount, acctNum;
Money customerMoney;
BankAccount(String name, int accNo, int bal) {
this.name = name;
this.acctNum = accNo;
this.balance = bal;
this.customerMoney = new Money();
}
void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + acctNum);
System.out.println("Balance:" + balance);
}
void displayBalance() {
System.out.println("Balance:" + balance);
}
public Money getMoney(){
return this.customerMoney;
}
}
The biggest problem is at statement balance=0
public static int accountNumber, balance=0;
^^^^^^^^^
Every time when you are going to insert amount, your balance is ZERO.
You should have used setDeposit(input.nextInt())
In public void setBalance(int b), b = balance; should have been balance = b;
Also, your amount, balance variables should be Float instead of int as balance/amount can be 23434.22.
I would remove all the public static int variables that you are using. These are going to cause confusion because it's much harder to follow what their values are as the program executes. Best to encapsulate your logic into BankAccount using private variables and public methods to modify them.
I would, personally, eliminate the Money class from your code. It's just going to cause confusion and with your simplified logic is not required. Let's assume the account holds some arbitrary count of 'money' but there is no real-life money actually backing it up - (kind of like real life, it's just 'numbers on a screen' right?) - in this case we wouldn't need the Money class, just an int for our BankAccount's balance.
Without trying to make too many changes to your underlying functionality, I rewrote as the below two classes:
A BankAccount class:
package banking;
public class BankAccount {
/**
* The balance of this account. <br/>
* Assumes integer money (Floating point math is horrible and who really
* needs pesky pence or cents right?!)
*/
private int balance;
/**
* The account number
*/
private final int acctNum;
/**
* Name of the account holder
*/
private final String name;
/**
* Construct our basic account with an account number, account holder and
* starting balance.
*
* #param name
* #param accNo
* #param bal
*/
public BankAccount(String name, int accNo, int bal) {
this.name = name;
this.acctNum = accNo;
this.balance = bal;
}
/**
* Make a deposit to this account by adding a fixed sum to the existing
* balance. <br/>
*
* #param amount
*/
public void deposit(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("You cannot deposit zero or less");
} else {
this.balance += amount;
}
}
/**
* Make a withdrawal from this account by subtracting a fixed amount from
* the existing balance. <br/>
*
* #param amount
*/
public void withdraw(int amount) {
if (amount > balance) {
throw new IllegalArgumentException("Insufficient Funds");
} else if (amount <= 0) {
throw new IllegalArgumentException("You cannot withdraw zero or less");
} else {
balance -= amount;
}
}
/**
* Get the account holder name.
*
* #return
*/
public String getName() {
return name;
}
/**
* Get the current account balance.
*
* #return
*/
public int getBalance() {
return balance;
}
/**
* Get the account identifier for this account.
*
* #return
*/
public int getAcctNum() {
return acctNum;
}
/**
* Debug print method.
*/
public void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + acctNum);
System.out.println("Balance:" + balance);
}
}
And the main class:
package banking;
import java.util.Random;
import java.util.Scanner;
public class BankMain {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String customerName = input.nextLine();
Random randomGenerator = new Random();
int acctNo = randomGenerator.nextInt(100000);
System.out.println("Enter Initial Balance: ");
int balance = input.nextInt();
BankAccount acct = new BankAccount(customerName, acctNo, balance);
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
int menu;
do {
final int transaction;
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
System.out.print("Enter depost amount:");
transaction = input.nextInt();
acct.deposit(transaction);
break;
case 2:
System.out.println("Current Account Balance=" + acct.getBalance());
System.out.print("Enter withdrawal amount:");
transaction = input.nextInt();
try {
acct.withdraw(transaction);
} catch (IllegalArgumentException iaEx) {
System.out.println(iaEx.getMessage());
}
break;
case 3:
acct.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
}
This is still far from perfect, but I feel it's easier to follow for having the static variables and Money class removed.
You have many problems with the code e.g. none of your fields should be static, but the main one is that you have multiple duplicated fields.
e.g. In Money you have
public static int accountNumber, balance=0;
static int amount;
static String name;
and in BankAccount you have
static String name;
public static int balance, amount, acctNum;
Money customerMoney;
which means you have multiple fields called name, balance and amount. Some of the code uses the first group of fields and some of the code uses the second. You also have a customerMoney which is not updated directly.
To avoid confusion I suggest you have each field be non-static and in only one place. Remove the customerMoney as you might be tempted to use it ;)