I need to create a void method for withdrawals that accepts a double, along with setting a balance + the amount entered parsed as a double.
I have typed this so far: public void; I am unsure how to continue.
This is the whole code that I have:
// Create a class named BankAccount
public class BankAccount {
// Create a double named balance
double balance;
// Create a no-arg constructor named BankAccount
// Set balance to 0.0
public BankAccount()
{
balance = 0.0;
}
// Create a constructor named BankAccount that accepts a BankAccount object
public BankAccount(double initialBalance)
{
// Set balance to the balance of the BankAccount object
balance = initialBalance;
}
// Create a constructor named BankAccount that accepts a double
// Set balance to the user's entered double
public BankAccount(double userBalance)
{
balance = userBalance;
}
// Create a constructor named BankAccount that accepts a string
// Set balance to the user's entered string parsed as a double
public BankAccount(String[])
{
double balance = 0;
}
// Create a void method for deposits that accepts a double for the amount
// Set balance to balance + the amount entered
public void deposit(double depositAmount)
{
balance += double depositAmount;
}
// Create a void method for deposits that accepts a string for the amount
// Set balance to balance + the amount entered parsed as a double
public void deposit(String[])
{
balance += double depositAmount;
}
// Create a void method for withdrawals that accepts a double for the amount
// Set balance to balance - the amount entered
public void
(This is for an assignment. One of my classmates recommended this site to get some help and my teacher is pretty chill about looking for answers from different sites.)
Edit: I finished the code but am getting some errors.
Here are the errors I'm getting:
./BankAccount.java:32: error: <identifier> expected
public BankAccount(String[])
^
./BankAccount.java:24: error: constructor BankAccount(double) is already defined in class BankAccount
public BankAccount(double userBalance)
^
Main.java:19: error: cannot find symbol
account1 balance = 1200;
^
symbol: class account1
location: class Main
./BankAccount.java:69: error: cannot find symbol
balance = userBalance;
^
symbol: variable userBalance
location: class BankAccount
4 errors
If you want to create a method, you must have a return type. It should be after the access modifier and before the method name.
For clarifications, void is a return type that indicates that your method isn't required to return a data. (Implicitly, it just returns null)
From your instance, you can have the following method to add the value of the parameter depositAmount to the global variable balance:
public void deposit(double depositAmount) {
balance += depositAmount;
}
From your example, you don't need to declare the variable type (double) again because it was already declared on the parameter.
For your other requirement, you can have the following method to deposit an array of depositAmounts in String:
public void deposit(String [] depositAmounts) {
for (int i = 0; i < depositAmounts.length; i++) {
balance += Double.parseDouble(depositAmounts[i]);
}
}
To create a withdrawal method you can have the following method:
public void withdraw(double withdrawAmount) {
balance -= withdrawAmount;
}
Cheers.
You'd want to continue as follows:
public void withdraw(double amount) {
balance -= amount;
}
The method withdraw is of a void return type, which means it does not return anything. If you would like it to return a balance, you'd need to type double instead of void and add a return value (return balance;). It's not neccesary or needed of course, I'm just pointing out the distinction of what void means.
As it stands, the code above will take in one argument - amount to be withdrawn - and subtracts that amount from the balance.
Related
So currently, I'm struggling to make one particular program in eclipse for an assignment, while I am able to make most of the program, I seem to struggle with the no argument part of the program as well as bringing the pieces of the first class into the second for a brief moment. Here is my code for the first class
// Preparation of the input
import java.util.Scanner;
public class primarySetUp {
public static void main(String[] args) {
// Variable Declaration
double userBagNumber;
double userBagWeight;
// Create Scanner
Scanner input = new Scanner(System.in);
java.util.Date date = new java.util.Date();
// Opening Statement
System.out.println("Welcome to the Coffee Sales Simulation!");
// Get User Input
System.out.println("How heavy do you want the bags to be?");
userBagWeight = input.nextDouble();
System.out.println("How many bags do you want?");
userBagNumber = input.nextDouble();
// Get output
// Date
System.out.println("Todays date: ");
System.out.printf("%tB %<te, %<tY", date);
System.out.println(""); // spacer
// Original Inputs
System.out.printf("\nNumber of Bags: %3.0f", userBagNumber);
System.out.printf("\nWeight of Each Bag: %3.2f", userBagWeight);
System.out.print(" lbs");
// Calling of the Class
secondarySetUp mysecondarySetUp = new secondarySetUp(userBagWeight, userBagNumber);
// End Program
System.out.println("\nThank you for shopping with us!");
}
}
and here is my code for the second class, which is full of errors in this case.
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
public secondarySetUp(double userBagWeight, double userBagNumber) {
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// No argument pricing
public Sale() {
singleBagger = 1;
pounderBagger = 1;
}
// First constructor receiving No argument pricing
public Sale(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
If you have any sort of fixes I could apply, please let me know; I am planning on adding the print statements for the rest of the arguments as well, but I'd like to get Sale() fixed up first.
I see a problem in getSale() where you are trying to use userBagWeight, but that variable doesn't exist outside the constructor parameters, which could create a lot of problems since other methods are calling on it. The constructor taking
double userBagWeight, double userBagNumber, yet it's not assigning them to any fields or doing anything with them.
I missed the part where you are treating Sale() as a constructor, but those are no constructors. The constructor is named after your class name.
public secondarySetUp(double userBagWeight, double userBagNumber)
change Sale() to secondarySetUp and you will be fine.
here how your class should be like :
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
double userBagWeight, userBagNumber;
public secondarySetUp(double userBagWeight, double userBagNumber) {
this.userBagWeight = userBagWeight;
this.userBagNumber = userBagNumber;
singleBagger = 1;
pounderBagger = 1;
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// First constructor receiving No argument pricing
public secondarySetUp(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
this is a keyword to tell the program that we want to use the field "instance variable", if we have a method with parameter that have same name as a field name, then to tell them apart we tell the program this.fieldName to know which one we talking about.
I've written a small assignment where I've created a TimeDepositAccountand am creating a method to get the current balance, new balance after calculating the interest, and then a withdraw method. I'm stuck on printing the new balance to System.out since for some reason, I'm unable to get the new balance. Second, I want to use a local variable for the withdraw method since in our upcoming test we'll be tested on those, but we never did them in class so I'm unsure as how to go about that.
public class TimeDepositAccount {
//instance fields
private double currentBalance;
private double interestRate;
//Constructors
public TimeDepositAccount(){}
public TimeDepositAccount(double Balance1, double intRate){
currentBalance = Balance1;
interestRate = intRate;
}
//Methods
public double getcurrentBalance(){
return currentBalance;
}
public void newBalance(){
currentBalance = currentBalance * (1 + (interestRate/ 100) );
}
public double getintRate(){
return interestRate;
}
public String toString(){
return "TimeDepositAccount[ currentBalance = "+getcurrentBalance()+",
interestRate = "+getintRate()+"]";
}
public class TimeDepositAccountTester{
public static void main (String[] args){
TimeDepositAccount tda = new TimeDepositAccount(10,2);
double currentBalance = tda.getcurrentBalance();
System.out.println(currentBalance);
tda.newBalance();
System.out.print(currentBalance);
}
}
I wanted the output to first print 10.0, then 10.2, but instead I get 10.0 both times.
You would want to change your main method to the following:
public static void main (String[] args){
TimeDepositAccount tda = new TimeDepositAccount(10,2);
double currentBalance = tda.getcurrentBalance();
System.out.println(currentBalance);
tda.newBalance();
currentBalance = tda.getcurrentBalance();
System.out.print(currentBalance);
}
The variable currentBalance stores what the balance was when you defined it. Changing the balance of tda does not change the value of currentBalance. Thus, to update the value of currentBalance, you need to run currentBalance = tda.getcurrentBalance(); again.
I'm pretty new to Java script writing and I'm trying to fix four errors I get when I compile my code. I'm so frustrated, what am I doing wrong?
The Errors are:
SavingsAccount.java:25: error: no suitable constructor found for BankAccount(String,double,double)
super(name, balance, interestRate);
^
constructor BankAccount.BankAccount(String,double) is not applicable
(actual and formal argument lists differ in length)
constructor BankAccount.BankAccount(String) is not applicable
(actual and formal argument lists differ in length)
SavingsAccount.java:29: error: cannot find symbol
Interest = balance * (interestRate / 12);
^
symbol: variable Interest
location: class SavingsAccount
SavingsAccount.java:29: error: cannot find symbol
Interest = balance * (interestRate / 12);
^
symbol: variable interestRate
location: class SavingsAccount
SavingsAccount.java:31: error: cannot find symbol
this.deposit(interest);
^
symbol: variable interest
location: class SavingsAccount
4 errors
My code:
import java.util.Scanner; // Needed for the Scanner class
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.logging.Level;
import java.util.logging.Logger;
class SavingsAccount extends BankAccount {
static {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate; // The annual interest rate
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
// Get the annual interest rate.
interestRate = keyboard.nextDouble() * .001;
// post monthly interest by multiplying current balance
// by current interest rate divided by 12 and then adding
// result to balance by making deposit
}
public SavingsAccount(String name, double balance, double interestRate)
throws NegativeAmountException {
super(name, balance, interestRate);
}
public void postInterest() {
Interest = balance * (interestRate / 12);
try {
this.deposit(interest);
// and current account balance (use printStatement from
// the BankAccount superclass)
// following this also print current interest rate
} catch (Exception ex) {
Logger.getLogger(SavingsAccount.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
BankAccount.java (This one works with no errors):
class BankAccount {
public String name;
public double balance;
public BankAccount(String name, double balance) throws NegativeAmountException {
this.name = name;
this.balance = balance; // set name and balance
if (balance < 0) { // make sure balance is not negative
throw new NegativeAmountException("Can not create an account with a negative amount."); // throw exception if balance is negative
}
}
public BankAccount(String name) throws NegativeAmountException {
this(name, 0); // set name and use 0 balance
}
// update balance by adding deposit amount
// make sure deposit amount is not negative
// throw exception if deposit is negative
public void deposit(double amount) throws NegativeAmountException {
if (amount > 0) {
this.balance += amount;
}
else {
throw new NegativeAmountException("Deposit amount must not be negative");
}
}
// update balance by subtracting withdrawal amount
// throw exception if funds are not sufficient
// make sure withdrawal amount is not negative
// throw NegativeAmountException if amount is negative
// throw InsufficientFundsException if balance < amount
public void withdraw(double amount) throws InsufficientFundsException, NegativeAmountException {
if (amount > getBalance()) {
throw new InsufficientFundsException("You do not have sufficient funds for this operation.");
}
else if (amount < 0) {
throw new NegativeAmountException("Withdrawal amount must not be negative.");
}
else {
this.balance -= amount;
}
}
// return current balance
public double getBalance() {
return this.balance;
}
// print bank statement including customer name
// and current account balance
public void printStatement() {
System.out.println("Balance for " + this.name + ": " + getBalance());
}
}
You have 2 errors in code:
About first error Java compiler notes that in superclass BankAccount you haven't constructor with 3 variables (your call super(name, balance, interestRate); in SavingAccounts class. You should:
add corresponding constructor to BankAccount class or
use existent constructor from BankAccount class and keep interestRate as SavingAccounts class variable.
Second error makes 3 error by compiler opinion: in code Interest = balance * (interestRate / 12); you lost local variable. After fix it (seems that should be double interest = balance * (interestRate / 12);) you'll remove 3 errors.
There are multiple problems with your code.
You normally do not use a static block as you do. You may want to write a public static void main(String... args).
The actual problem with your code is the superclass-constructor call via super(...). BankAccount does not provide an accessible constructor with the specified signature (String, double, double). Either there is no such constructor or the constructor is not visible (see this for details).
For the other errors regarding Interest, please look at Pavel's answer.
Furthermore, there are some general accepted coding standards for Java, some can be found here. Please respect them.
Hello I'm new to programming and a first time poster here. I'm having trouble getting a Java application to display the correct values assigned via Set methods in a public class. Specifically the CreatePurchase application returns 0 for all 3 user defined variables (invoiceNumber, saleAmount, salesTax) which are Set in the Purchase public class.
Set and display the values here
public class Purchase
{
private int invoiceNumber;
private double saleAmount;
private double salesTax;
public int getInvoiceNumber()
{
return invoiceNumber;
}
public void setInvoiceNumber(int inv)
{
inv = invoiceNumber;
}
public double getSaleAmount()
{
return saleAmount;
}
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
public double getSalesTax()
{
return salesTax;
}
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax;
}
public static void displayPurchase(Purchase aPurch)
{
System.out.println("Purchase invoice number is " + aPurch.getInvoiceNumber() + "and the sale amount is " + aPurch.getSaleAmount() + "the taxable amount is " +aPurch.getSalesTax());
}
}
This is the CreatePurchase class that prompts the user for the variables and calls the method to display the values for the new object
import java.util.Scanner;
public class CreatePurchase
{
public static void main(String args[])
{
Purchase aPurchase;
aPurchase = getPurchaseInfo();
Purchase.displayPurchase(aPurchase);
}
public static Purchase getPurchaseInfo()
{
Purchase tempPur = new Purchase();
int invoice;
double value;
double value2;
Scanner input = new Scanner(System.in);
System.out.println("Enter the invoice number:");
invoice = input.nextInt();
while(invoice < 1000 || invoice > 8000)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + invoice);
System.out.println("Please enter a whole number between 1000 and 8000");
invoice = input.nextInt();
}
tempPur.setInvoiceNumber(invoice);
System.out.println("Enter the amount of the sale:");
value = input.nextDouble();
value2 = (value * .05);
while(value < 0)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + value);
System.out.println("Please enter a non negative number");
value = input.nextDouble();
value2 = (value *.05);
}
tempPur.setSaleAmount(value);
tempPur.setSalesTax(value2);
return tempPur;
}
}
Any direction or advice on how to get the values entered to set and display properly would be greatly appreciated.
The setter needs to assign the new value to the instance field.
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
Yours do the opposite now, switch the assignment around:
public void setSaleAmount(final double sale)
{
this.saleAmount = sale;
}
You can also optionally add final to the parameter (since you don't intend to change it), and make it clear what the instance field is by using this.. Purely optional, but good practice, and in this case either addition would have resulted in a compile-time error to alert you of the mistake.
Your assignments are wrong(for the setters).
It should be salesTax that is set:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax; /* wrong assignment(for the purpose) */
}
And so on for your other class variables.
Remember: Setters and Getters are used to modify a class' variables.
All setters need to be modified as below:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
//tax = salesTax; <-- This line is wrong..
this.salesTax= tax ; // Change this line and it should work...
}
public void setInvoiceNumber(int inv)
{
//inv = invoiceNumber ; --> Invalid setting
this.invoiceNumber = inv; // Correct setting
}
public void setSaleAmount(double sale)
{
//sale = saleAmount; --> Invalid setting
this.saleAmount = sale; // Correct setting
}
Reason:
tax is local variable which is specific to the method setSalesTax.
salesTax is global variable for the object.
While setting value in your object, you need to set it/assign in the global variable salesTax
To avoid confusions, The best way to use a setter would be:
Object Class:
private double amount;
public void setAmount (double amount)
{
this.amount = amount;
}
It is because you do not set the new Value to your object value.
The correct way would be
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
salexTax = tax; //THIS is the mistake
}
Everytime you want to assign a value to an Object, Integer, or whatever, it goes from left to right. So, if you write:
int value=5;
int value2=10;
value2=value;
Value2 is 5 then.
Your setter method is wrong. You must use actual variable on LHS instead of formal argument.
for Ex, setInvoceNumber method should be like below :
public void setInvoiceNumber(int inv)
{
invoiceNumber = inv ;
}
Here inv is formal argument while invoiceNumber is actual variable which is going to store your value in object. You were assigning value of invoiceNumber to inv variable which has no effect in your code. Same goes for all your setter method.
//*******************************************************
// Account.java
//
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
//*******************************************************
import java.util.Random;
public class Account
{
private double balance;
private String name;
private long acctNum;
//----------------------------------------------
//Constructor -- initializes balance, owner, and account number
//----------------------------------------------
public Account(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}
//----------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//----------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
}
//----------------
//Track how many accounts
//----------------
private static int numAccounts=0;
{
numAccounts++;
}
public static int getNumAccounts()
{
return numAccounts;
}
//----------------------------------------------
// Adds deposit amount to balance.
//----------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//----------------------------------------------
// Returns balance.
//----------------------------------------------
public double getBalance()
{
return balance;
}
// Get name of account
public String getName()
{
return name;
}
//----------------------------------------------
// Returns account number.
//----------------------------------------------
public long getAcctNumber()
{
return acctNum;
}
//----------------
//Void and close the accounts
//----------------
public void close()
{
balance = 0;
name += "CLOSE";
numAccounts--;
}
//----------------
//Consolidating accounts
//----------------
public static Account consolidate(Account acct1,Account acct2)
{ Account newAccount=null;
if((acct1.getName()).equals(acct2.getName()))
if(acct1.getAcctNumber()!=acct2.getAcctNumber())
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
Random generator = new Random();
acctNum= generator.nextInt();
acct1.close();
acct2.close();
}
else
System.out.println("Not allow,same account number");
else
System.out.println("Can't use other people account");
return newAccount;
}
//----------------------------------------------
// Returns a string containing the name, account number, and balance.
//----------------------------------------------
public String toString()
{
return "Name: " + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
Please look at the //consolidate section. What I'm trying to do is, consolidate acct1 and acct2 into one new account, with the restrictions that is acct1 and acct2 has to has the same name, acct1 and acct2 account number has to be different from each other, and if those are met, create a new account with a new balance from the two old account, keep the same name and also randomly generate a new account number. Is there something missing in my code? It wont compile. These are errors i got
Account.java:95: ')' expected
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
^
Account.java:95: illegal start of expression
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
^
String owner should just be acct1.getName() or whatever function retrieves the name.
Also, the line acctNum = generator.nextInt(); will fail as acctNum isn't defined in that context. Furthermore, you don't set the account number of newAccount to be this acctNum variable.
I suggest you change it to this:
newAccount.setAcctNumber(generator.nextInt());
The compile error at the line
newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner)
is because String owner is a declaration that should be used in a method signature, as you did above. When you actually make a call to the constructor, though, you need to send a String parameter in.
The compiler is complaining because what you are actually doing at this line is declaring a String variable named owner. Java won't allow that in a method call.
Finbarr is right; use the method to get the name of the account instead.