Having an issue receiving the "Just Tax." Program compiles, will not calculate sales tax on output - simply returns a "0." The "Sale" method (not within listed code) will acknowledge and print the amount of the sale, however. Not sure what I'm doing incorrectly. Thanks!
//...
Purchase saleAmount = new Purchase();
//...
System.out.println("Please enter a positive (+) number for the sale amount: $");
double saleAmt = input.nextDouble();
saleAmount.setSale(saleAmt);
//...
System.out.println("The 5% tax applied is: " + saleAmount.getJustTax());
public class Purchase
//all data types have been declared
final double SALES_TAX = 0.05;
{
//Initial Sale Cost
public double getSale()
{
return sale;
}
public void setSale(double amount)
{
amount = sale;
}
//Get Just Sales Tax
public double getJustTax()
{
return justTax;
}
public void setJustTax(double sale)
{
justTax = (sale * SALES_TAX);
}
}
The assignment in your setSale method is backwards. Currently, it assigns whatever is in sale to your local variable amount.
Change
public void setSale(double amount)
{
amount = sale;
}
to
public void setSale(double amount)
{
sale = amount;
}
public void setSale(double amount)
{
amount = sale;
}
This is causing the issue. What you're currently doing is taking the method argument and assigning your sale variable to it. (I cannot see it in the code however).
public void setJustTax(double sale)
{
justTax = (sale * SALES_TAX);
}
This means when the above code is called, sale still has no value to it and I'll guess that sale is instantiated with 0.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have created a Java program for banking, which allows the user to deposit funds, withdraw funds, and check their balance.
However, I would like to be able to print the convToString data (name, accNo, balance) whenever the getBalance() command is called. This would be much more effective than having to type System.out.println(JohnSmith.convToString()+"\n") each time I want to print the account information.
Any advice on how best to clean my code up and make this happen?
My full source code follows...
package week1src;
public class BankAccount {
private String name;
private int accNo;
private double balance;
// Constructor to initialise all 3 instance variables
public BankAccount(String n, int a, double amount)
{
name = n;
accNo = a;
balance = amount;
}
// Constructor to set default opening account balance to zero
public BankAccount(String n, int a)
{
name = n;
accNo = a;
balance = 0.00;
}
/* --------------------
Return a String containing all the information of the account based on account name input
--------------------*/
public String convToString( )
{
return("Account name: " + this.name + ", Account number: " + this.accNo + ", Available balance: " + "£" + this.balance);
}
/* --------------------
Method to deposit funds by adding "amount" to balance
--------------------*/
public void deposit(double amount) {
if (amount <= 0) {
// returns an error message is value entered is negative
System.err.println("Cannot deposit negative amounts. Please enter a different amount.");
}
else {
this.balance += amount;
System.out.format("£%.2f has been deposited\n", amount);
}
}
/* --------------------
Method to withdraw funds by subtracting "amount" from balance
--------------------*/
public void withdraw(double amount) {
if (this.balance >= amount) {
this.balance -= amount;
System.out.format("£%.2f has been withdrawn\n", amount);
}
else { // returns an error message if withdrawal with put account balance below 0
System.err.println("Transaction cancelled due to insufficient funds. Check balance or deposit funds.");
}
}
/* --------------------
Method used to display account balance
--------------------*/
public double getBalance() {
return balance;
// i want to print the convToString info whenever getBalance() is called.
}
}
package week1src;
public class BankMain {
public static void main(String[] args) {
BankAccount JohnSmith = new BankAccount("John Smith", 1, 00); // create an account object (acc name, acc no, opening balance)
//BankAccount DavidJones = new BankAccount("David Jones", 2, 1000); // create an account object (acc name, acc no, opening balance)
System.out.println(JohnSmith.convToString()+"\n"); // will display acc name, acc number, and current balance (£0)
JohnSmith.deposit(100); // deposit £100
JohnSmith.deposit(-50); // will return error due to negative value
JohnSmith.deposit(10); // deposit £10
JohnSmith.withdraw(25); // withdraw £25
JohnSmith.withdraw(90); // will return error as balance will go <0
System.out.println(JohnSmith.getBalance()); // display balance
JohnSmith.withdraw(70); // withdraw £70
System.out.println(JohnSmith.convToString()+"\n"); // will display acc name, acc number, and current balance (£15.00)
}
}
It can be achieved like this:
BankAccount.java:
public class BankAccount {
private String name;
private int accNo;
private double balance;
// Constructor to initialise all 3 instance variables
public BankAccount(String n, int a, double amount) {
name = n;
accNo = a;
balance = amount;
}
// Constructor to set default opening account balance to zero
public BankAccount(String n, int a) {
name = n;
accNo = a;
balance = 0.00;
}
/* --------------------
Method to deposit funds by adding "amount" to balance
--------------------*/
public void deposit(double amount) {
if (amount <= 0) {
// returns an error message is value entered is negative
System.err.println("Cannot deposit negative amounts. Please enter a different amount.");
} else {
this.balance += amount;
System.out.format("£%.2f has been deposited\n", amount);
}
}
/* --------------------
Method to withdraw funds by subtracting "amount" from balance
--------------------*/
public void withdraw(double amount) {
if (this.balance >= amount) {
this.balance -= amount;
System.out.format("£%.2f has been withdrawn\n", amount);
} else { // returns an error message if withdrawal with put account balance below 0
System.err.println(
"Transaction cancelled due to insufficient funds. Check balance or deposit funds.");
}
}
/* --------------------
Method used to display account balance
--------------------*/
public double getBalance() {
return balance;
// i want to print the convToString info whenever getBalance() is called.
}
public void printAccountInfo() {
System.out.println(this);
}
#Override
public String toString() {
return "Account name: " + this.name + ", Account number: " + this.accNo
+ ", Available balance: " + "£" + this.balance;
}
}
BankMain.java:
package your.package.here;
public class BankMain{
public static void main(String[] args) {
BankAccount JohnSmith = new BankAccount("John Smith", 1,
0); // create an account object (acc name, acc no, opening balance)
//BankAccount DavidJones = new BankAccount("David Jones", 2, 1000); // create an account object (acc name, acc no, opening balance)
JohnSmith.printAccountInfo();
JohnSmith.deposit(100); // deposit £100
JohnSmith.deposit(-50); // will return error due to negative value
JohnSmith.deposit(10); // deposit £10
JohnSmith.withdraw(25); // withdraw £25
JohnSmith.withdraw(90); // will return error as balance will go <0
System.out.println(JohnSmith.getBalance()); // display balance
JohnSmith.withdraw(70); // withdraw £70
JohnSmith.printAccountInfo();
}
}
It seems reasonable to create a separate reusable printing method, that will do all what you need. And instead of creating your convToString method, you can just override toString and then use it in a way that I've posted. This is built in java mechanism that do exactly what you need.
Tricky thing here is when you're calling System.out.println(this); default behavior is to call toString method on that object that you've passed to the System.out.println method.
And here is the magic happens, you just override toString, and then call System.out.println on your object instance. It will then take your instance and call your overrided toString on that.
Please, have a look.
I tried searching for this answer and found several answers that were similar to what I am looking for, but I can't seem to apply the suggestions provided on unrelated data to my specific program.
I need to take this working code I have created (a program to calculate an employee's annual compensation) and adjust it in a way that shows two classes (per the instructions of my homework assignment). The output given is exactly what I want, I just need help to reorganize the code so there is more than the main class. Is this something I can get help with here?
Here is my working code:
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
double commissionPercentage = 0.06;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
double totalCompensation = (value * commissionPercentage) + salary;
System.out.println("Your annual compensation is: " + "$" + totalCompensation);
}
}
Thanks in advance.
create a class Employee with salary and commissionPercentage as the fields.
In constructor take the salary and commision% of employee and initate the fields.
in this class Employee create a method which will take vavlue as input and will calculate the compensation and return it.
So from main create the instance of Employee class and call the calculateMethod.
I would structure it with these classes:
AnnualCompensationCalculator which will do the computation for you as a utility class, and
AnnualCompensation main class which would be focused on requesting for the user input (and would call the calculator).
Suppose you can move the logic inside new class.
AnnualCompensationCalculator.java
public class AnnualCompensationCalculator{
private static double commissionPercentage = 0.06;
public static double calculateCompensation(double sales ,double salary){
return((sales * commissionPercentage) + salary);
}
}
AnnualCompensation .java
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
System.out.println("Your annual compensation is: " + "$" + AnnualCompensationCalculator.calculateCompensation(value,salary));
}
}
Following Object Oriented Programming, I suggest you create a new class Employee that holds the salary and compensation percentage of an employee, which also has a method for calculating the compensation.
Like this:
class Employee {
private double salary;
private double commPercent;
public Employee(double salary, double commPercent) {
this.salary = salary;
this.commPercent = commPercent;
}
public double calculateCompensation(double totalSales) {
return (totalSales * commPercent) + salary;
}
/* Setters & Getters */
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getCommPercent() {
return commPercent;
}
public void setCommPercent(double commPercent) {
this.commPercent = commPercent;
}
}
Then have your main class use this Employee class to do all the work:
public class AnnualCompensation {
public static void main(String[] args) {
//Initialize an Employee object
Employee emp = new Employee(60000, 0.06);
//Create command output for the user to get directions to enter value
System.out.print("Enter total amount of sales for the year: ");
Scanner input = new Scanner(System.in);
double salesAmt = input.nextDouble();
//Calculate the compensation based on the user input then print it
System.out.println("Your annual compensation is: $"
+ emp.calculateCompensation(salesAmt));
}
}
The program I am working on currently runs successfully but it doesn't execute part of my program and it shows no errors.
The prompt was:
"Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java."
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
double tax = .05;
double totalamount;
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
while (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
}
while (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
}
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount(double totalAmount) {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
double totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
I have spent hours trying to figure out what I need to fix in order to get my display method to work. The program runs successfully, and there are no errors, so I am not sure what to even try to fix.
(Sorry if my code or question doesn't make sense.)
I would massively refactor your code if given the chance. First, the CreatePurchase class should be a simply POJO (plain old Java object), containing state for the invoice number, purchase amount, and sales tax, along with getter and setter methods for accessing and changing that state. Next, the main() method within this class will instantiate a CreatePurchase object for storing the user input. A big change I made was in how the code handles user inputs. My code below uses two while loops to poll the user for a correct invoice number (between 1000 and 8000) and amount (non negative), and only then proceeds with the remainder of the method. Finally, the CreatePurchase object created is used to output the result to the console.
public final class CreatePurchase {
private int invoiceNum;
private double amount;
private double totalamount;
// I am hard-coding the sales tax as 5%, as you did in your question,
// though this code can easily be modified if you also want to input the tax
private final double tax = .05;
public int getInvoiceNum() {
return invoiceNum;
}
public void setInvoiceNum(int invoiceNum) {
this.invoiceNum = invoiceNum;
}
public double getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
public static void main(String[] args) {
CreatePurchase cp = new CreatePurchase();
Scanner input = new Scanner(System.in);
// these next two do-while loops will continue polling the user
// until he enters a valid input
do {
System.out.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
} while (invoiceNum < 1000 || invoiceNum > 8000);
cp.setInvoiceNum(invoiceNum);
do {
System.out.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
} while (amount < 0);
totalamount = amount*(1 + tax);
cp.setAmount(amount);
cp.setTotalAmount(totalAmount);
// now use the CreatePurchase object to print out
// details of the transaction
System.out.println("Your invoice number is:" + cp.getInvoiceNum() + ".");
System.out.println("Your sale amount is: " + cp.getAmount() + ".");
System.out.println("Your sale amount after tax is: " + cp.getTotalAmount() + ".");
}
}
You declared method public void display(int invoiceNum, double amount, double totalAmount) but you never actually used it.
try the below code, this should help!
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
static double tax = .05;
static double totalAmount;
public void updatePurchase(final Purchase purchase) {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
if (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
updatePurchase(purchase);
}
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
if (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
updatePurchase(purchase);
}
setTotalAmount(tax, amount);
display(invoiceNum, amount, getTotalAmount());
}
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
new CreatePurchase().updatePurchase(completedPurchase);
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
My homework tells me to do this....
a. Create a class named Purchase. Each Purchase contains an invoice number,
amount of sale, and amount of sales tax. Include set methods for the invoice
number and sale amount. Within the set() method for the sale amount, calculate
the sales tax as 5% of the sale amount. Also include a display method that displays
a purchase’s details. Save the file as Purchase.java.
b. Create an application that declares a Purchase object and prompts the user
for purchase details. When you prompt for an invoice number, do not let the
user proceed until a number between 1,000 and 8,000 has been entered.
When you prompt for a sale amount, do not proceed until the user has entered
a nonnegative value. After a valid Purchase object has been created, display
the object’s invoice number, sale amount, and sales tax. Save the file as
CreatePurchase.java.
This is what I have so far......
import java.util.*;
public class Purchase{
public double invoiceNumber;
public double saleAmount;
public double salesTax;
public void setInvoice(double number){
this.invoiceNumber = number;
}
public void saleAmount(double sale){
this.salesTax = sale*.05;
this.saleAmount = sale;
}
public void displayPurchase(){
System.out.print("Invoice Number " + invoiceNumber + " Sale Amount " + saleAmount + " Sales Tax " + salesTax);
}
}
import java.util.*;
public class CreatePurchase extends Purchase{
Scanner input = new Scanner(System.in);
double inputSale = input.nextDouble();
double inputNumber = input.nextDouble();
public void valueChecker(){
if(1000 >= inputSale && inputSale <= 8000){
saleAmount(inputSale);
invoiceChecker();
}
else if(inputSale <= 0){
System.out.print(" Not a valid invoice ");
}
}
public void invoiceChecker(){
setInvoice(inputNumber);
displayPurchase();
}
public static void main(String[] args){
}
}
Why isn't this working?
because you haven't called anything in main method. Your main method is empty.
public static void main(String[] args){
// you need to call other methods from here
CreatePurchase purchaseObject = new CreatePurchase();
purchaseObject.valueChecker();// or whatever method you want to call depending upon your logic.
}
import java.util.Scanner;
public class CreatePurchase extends Purchase {
public void invoiceChecker(double inputnumber, CreatePurchase cp) {
cp.setInvoice(inputnumber);
cp.displayPurchase();
}
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
double inputSale = input.nextDouble();
double inputNumber = input.nextDouble();
CreatePurchase cp = new CreatePurchase();
System.out.println(inputSale + " " + inputNumber);
if (inputSale >= 1000.0 && inputSale <= 8000.0) {
cp.saleAmount(inputSale);
cp.invoiceChecker(inputNumber, cp);
} else if (inputSale <= 0.0) {
System.out.print(" Not a valid invoice ");
}
}
}
TestInput and Output;
1500.2
3.0
1500.2 3.0
Invoice Number 3.0 Sale Amount 1500.2 Sales Tax 75.01
1)Do you get any compile time error?
Method invocation of java search for main method to execute but in the current
main method, It does not have anything to execute or NIL calls
public static void main(String[] args){
}
So nothing will be executed.Call the methods from the main method with the required inputs so that main methods will execute with the call invocation.
I created a main Java program that works like a bank giving a user their balance, withdrawls and transfer money.
import java.util.Scanner;
public class Lab12 {
public static void main(String[] args)
{
//Creating Two BankAccounts
BankAccount B1 = new BankAccount(1000, "ASU_ACCOUNT_110");
BankAccount B2 = new BankAccount(500, "ASU_ACCOUNT_100");
double amount;
Scanner scan = new Scanner(System.in);
//Account Deposit
System.out.println("Please Enter amount to deposit into ASU_ACCOUNT_110 Account");
amount = scan.nextDouble();
if(!B1.deposit(amount))
System.out.println("Error depositing amount in account. Please enter positive value.");
else
System.out.println("Successfully deposited $"+amount+". The current balance is "+B1.getBalance() );
//Account Withdrawal
System.out.println("Please Enter the amount you would like to withdraw from ASU_ACCOUNT_110");
amount = scan.nextDouble();
if(!B1.withdraw(amount))
System.out.println("Error withdrawing amount. You are either overdrawing or you have entered a negative value");
else
System.out.println("Successfully withdrew $"+amount+". The current balance is "+B1.getBalance());
//Account Transfer
System.out.println("Please Enter the amount you would like to transfer from ASU_ACCOUNT_110 to ASU_ACCOUNT_100");
amount = scan.nextDouble();
if(!B1.transfer(amount, B2))
{
System.out.println("Error transfering amount. You are either overdrawing or you have entered a negative value");
}
else
{
System.out.println("Successfully transferred $"+amount+".\nThe current balance in ASU_ACCOUNT_110 is "+B1.getBalance());
System.out.println("The current balance in ASU_ACCOUNT_100 is "+B2.getBalance());
}
//Account Display
System.out.println("\nThe details of the two accounts are:");
System.out.println("------------------------------------------");
display(B1);
System.out.println("------------------------------------------");
display(B2);
}
public static void display(BankAccount B)
{
System.out.println("The Account Number is "+B.getAccountNumber());
System.out.println("The balance is "+B.getBalance());
}
}
I created a second class that has methods and gets and calls the balances
public class BankAccount {
private String AccountNumber;
private double balance;
public BankAccount(double balance, String accountNumber)
{
this.balance = balance;
this.AccountNumber = accountNumber;
}
public boolean deposit(double amount)
{
return true;
}
public double getBalance()
{
return balance;
}
public boolean withdraw(double amount)
{
return true;
}
public boolean transfer(double amount, BankAccount b2)
{
return true;
}
public String getAccountNumber()
{
return AccountNumber;
}
}
The problem is that when I enter a negative amount for the deposit, withdrawal, transfer, I am not getting the error that I put in the main class
Any thoughts?
You do not check if the number is negative anywhere in BankAccount.deposit(double). You need to check if the code is negative like this:
public boolean deposit(double amount)
{
if(amount<0)
{
return false;
}else{
return true;
}
}
Your methods in BankAccount always return true. You can't expect them to sometimes signal failure unless you provide an implementation that does so.
For instance:
public boolean withdraw(double amount)
{
return true;
}
Will never signal failure because it always returns true. In order for your methods to behave the way you want them to, you must add more complex behavior. Something like:
public boolean withdraw(double amount)
{
//if the withdrawal is positive and does not exceed the balance
if (amount >= 0 && amount <= balance)
{
//remove money and signal success
balance -= amount;
return true;
}
//if either condition failed, signal failure
return false;
}
It looks like you simply forgot to implement these methods. Either that or you posses a fundamental misunderstanding of programming.
The deposit, withdraw and transfer methods always return true. Therefore you will never see the error message.