Java program not outputting correctly - java

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).

Related

How can I use a variable from all similar objects in an if statement (Java)?

I am a beginner in Java and I hit a small snag.
I'm writing some code for an imaginary bank, and I want to include all the accounts' balance into one if statement. I made a double called accountBalance that I use for each account.
For example, Josie.accountBalance = 1200. Josie is an object for the BankAccounts type I created.
I want to make an if statement, so that if the account balance is above 1000, the bank sends a message warning the account about this issue, and it refunds everything above 1000$.
I could just do an if statement for every account I create, and write my code there, but I was wondering if there was a way to write an if statement that applied to all the BankAccounts type, without having to specify the names.
Thanks.
Here's the code that I wrote.
package learnJavaNew;
import java.util.ArrayList;
public class BankAccounts {
final static double defaultBalance = 50;
final static double maxBalance = 1000;
static double oldBalance;
static int employees;
static double bankMoney;
static double accountBalance;
static double newBalance;
public static void main(String[] args) {
// Josie's Bank Account
BankAccounts Josie = new BankAccounts();
Josie.depositMoney(0);
Josie.accountBalance = defaultBalance + newBalance;
System.out.println(Josie.accountBalance);
Josie.withdrawMoney(25.64);
Josie.accountBalance = defaultBalance + newBalance;
System.out.println(Josie.accountBalance);
// Dan's Bank Account
BankAccounts Dan = new BankAccounts();
Dan.depositMoney(1000);
Dan.accountBalance = defaultBalance + newBalance;
System.out.println(Dan.accountBalance);
Dan.withdrawMoney(5);
Dan.accountBalance = defaultBalance + newBalance;
System.out.println(Dan.accountBalance);
// Accounts List
ArrayList<BankAccounts> accounts = new ArrayList<BankAccounts>();
accounts.add(Josie);
accounts.add(Dan);
System.out.println(accounts);
// Max Balance
if(accountBalance >= maxBalance) {
System.out.println("You have reached the maximum balance for your bank account, which is " + maxBalance + "$.");
System.out.println("You cannot deposit more money into this account.");
oldBalance = accountBalance;
accountBalance = 1000;
System.out.println("You have been refunded " + (oldBalance - accountBalance));
}
// New Balance
System.out.println(Dan.accountBalance);
System.out.println(Josie.accountBalance);
}
public void depositMoney(double depositedMoney) {
newBalance = depositedMoney;
}
public void withdrawMoney(double withdrawnMoney) {
newBalance = newBalance - withdrawnMoney;
}
}
This kind of depends on the result you want. If the above code gives you the right result, then it's fine. However I would probably do something like this, and omit the loop and the list entirely.
public void depositMoney(double depositedMoney) {
if( depositedMoney + accountBalance > 1000 )
System.out.println( "Maximum exceeded, not processed" );
else
accountBalance += depositedMoney;
}
Notice here that I've changed the previous operation of depositedMoney, including the fact that the method never updated accountBalance.
To refund money over an amount, you might return a value indicating the amount refunded.
public double depositMoney(double depositedMoney) {
double refund = 0;
if( depositedMoney + accountBalance > 1000 ) {
refund = depositedMoney + accountBalance - 1000;
accountBalance = 1000;
System.out.println( "Maximum exceeded, refund " + refund );
}
else
accountBalance += depositedMoney;
return refund;
}
Also, you really should be using instance variables. Remove the static keyword.
double bankMoney;
double accountBalance;
double newBalance;
This might be made clearer by a different object model.
I would propose a BankAccount class (not "a BankAccounts class" -- that would mean that an object is "a BankAccounts", a jarring concept) and a Bank class.
class BankAccount {
private String owner;
private double balance;
BankAccount(String s, double b) { owner = s; balance = b; }
String owner() { return owner; }
double balance() { return balance; }
void deposit(double amount) { … like before … }
void withdraw(double amount) { … like before … }
}
and
class Bank {
static List<BankAccount> accounts = new ArrayList<>();
public static void main(String[] args) {
// set up some accounts
BankAccount josie = new BankAccount("Josie", 0);
accounts.add(josie);
BankAccount dan = new BankAccount("Dan", 1000);
accounts.add(dan);
:
etc
:
// print them all
double total = 0;
for (BankAccount acnt : accounts) {
System.out.printf("Account %s : balance %s %n",
acnt.owner(), acnt.balance());
total += acnt.balance();
}
System.out.printf("Total value of accounts: %s %n", total);
}
}
The benefit of this approach is that it makes it clearer what operations are for a single account and what operations are on "all accounts".

why I'm unable to calculate amount of sale, and amount of sales tax?

public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax;
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
}
Your invoice number is:1234.
Your sale amount is: 10.0.
Your sales tax is: 0.0.-------Problem area
----jGRASP wedge2: exit code for process is 0.
----jGRASP: operation complete.
This will work...
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax = 0.0; // by default this is initialized to zero.
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
public static void main(String args[])
{
setSalePrice(10.0); // sets SalesTax to (100.0 * .05)
displaySalePrice();
}
}
Note that there are some stylistic issues with this class.
"SalesTax" starts with an upper case letter, which is supposed to be reserved for class (and interface) names. The correct spelling is "salesTax".
It lacks a constructor.
Example Constructor:
public Purchase(int invoiceN, double salesP, doubles salesT) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesT;
}
A purchase is a thing that doesn't change once it is made. Its data members are variable (change-able), but they should be invariable (final or constant).
final int invoiceNumber; // These are set in the Constructor.
final double salePrice; // Once they are set, they don't change.
final double salesTax;
The class has setters (which set/change the variables), but it lacks getters (which retrieve the values of the variables without changing them). In general, variables should be declared "private" and "final" whenever possible. So if I wrote this class, I would have written it like this:
Revised example:
public class Purchase
{
private final int invoiceNumber;
private final double salePrice;
private final double salesTax;
// Constructor
public Purchase(int invoiceN, double salesP) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesPrice * .05; // The Constructor can figure this out.
}
public int getInvoiceNumber()
{
return this.invoiceNumber; // "this." is optional
}
public double getSalePrice()
{
return this.salePrice();
}
public double getSalesTax()
{
return this.salesTax;
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + getInvoiceNumber() + ".");
System.out.println("Your sale amount is: " + getSalePrice() + ".");
System.out.println("Your sales tax is: " + getSalesTax() + ".");
}
public static void main(String args[])
{
Purchase shoesPurchase = new Purchase(1234, 10.00);
shoesPurchase.displaySalePrice();
}
}
You are never using the setSalePrice method, hence your SalesTax parameter is never being initialized. You could initialize it like so: double SalesTax = salePrice * 0.05;
You are never calling setSalePrice, so the sales tax never gets set
here's one way to correct this, though really you should probably call setSalePrice before calling displaySalePrice, rather than inside of it
public void displaySalePrice()
{
setSalePrice(salePrice);
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}

employee class will not calculate correctly

for the assignment, an employee has a ID number, hourly wage and works a certain # of hours. i need to calculate the gross income from those 2 values and then based of that there is withholding from the pay, in my code i believe all that is there but when i test my program i can only calculate the pay that was earned, the withholding and net pay come as a value of 0. i would appreciate any help on the issue, thank you.
// an employee has an ID, get paid an amout hourly and work an amount of hours
// tax is withheld depending on gross pay
public class Employee
{
//withholding calculation
public Employee(String empId, double hrsWrk, double hrPay)
{
employeeId = empId;
hoursWorked = hrsWrk;
hourlyPay = hrPay;
}
// access methods
public String getEmployeeId()
{
return employeeId;
}
public double getHoursWorked()
{
return hoursWorked;
}
public double getHourlyPay()
{
return hourlyPay;
}
public double getWithholding()
{
return withholding;
}
public double getIncome()
{
double income = hourlyPay * hoursWorked;
return income;
}
public double getNetPay()
{
double netPay = income - withholding;
return netPay;
}
// mutator methods
public void setId(String empId)
{
employeeId = empId;
}
public void setHoursWorked(double hrsWrk)
{
hoursWorked = hrsWrk;
}
public void setHourlyPay(double hrPay)
{
hourlyPay = hrPay;
}
//withholding calculator based on income
public void calcWithholding()
{
if(income <= 0)
{
withholding = 0.0;
}
else if(income >0 && income <= 300.0)
withholding = income*10.0/100;
else if(income >= 300.01 && income <= 400.0)
withholding = income*12/100;
else if(income >= 400.01 && income <= 500.0)
withholding = income*15/10;
else
withholding = income*20/100;
System.out.println("withholding is " + withholding);
}
public void displayWithholding()
{
calcWithholding();
System.out.println("Employee " + employeeId + " your income is " + getIncome() + " per week\n you have to pay " + getWithholding());
System.out.println("Employee " + employeeId + " your net income is " + getNetPay());
}
//instance fields
private String employeeId;
private double hoursWorked;
private double hourlyPay;
private double withholding;
private double income;
private double netPay;
}
here is the test program---------------------------------------------
import javax.swing.JOptionPane;
public class EmployeeTest
{
public static void main(String[] args)
{
String employeeId = JOptionPane.showInputDialog("Please enter your Employee ID");
String input = JOptionPane.showInputDialog("Enter your hourly wage");
double hourlyPay = Double.parseDouble(input);
input = JOptionPane.showInputDialog("How many hours have you worked this week?");
double hoursWorked = Double.parseDouble(input);
Employee richard = new Employee(employeeId, hoursWorked, hourlyPay);
richard.displayWithholding();
System.exit(0);
}
}
You're not calling getIncome until after calcWithHolding so the income variable is always zero during the calculation.
The current approach relies on side-effects from calling some of the accessors, this is generally considered to be a bad approach.
I would suggest one of the following
Ensure calculations done in the constructor (or called...)
Separate your concerns so that there is no confusion between data storage, object construction, data accessors and calculations.
Lazy initialization, so that calculated values are only calculated if they have never been accessed.

Trouble Calling and Using Java Methods

I just started learning Java and I'm trying to write a program based on an assignment sheet (gave this sheet at bottom of the post). However, I really don't quite understand how to use methods all that well. I've written my methods in the "Customer.java" class, and I'm trying to use them in my "TestCustomer.java" class. However, since I really don't know how to do this, it has turned out horribly. I've searched for information on this, but I just seem to keep making myself more confused. Is there any chance you guys could show me the correct way to use these methods, or at least point me in the right direction? Thank you a ton for any help you can provide.
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 Customer (String CustomerName, boolean taxable) {
}
public double calculateTax (double listSaleAmount) {
saleDiscount = listSaleAmount*saleRate;
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable == true) {
taxAmount = netSaleAmount*taxRate;
}
else {
taxAmount = 0.00;
}
saleTotal = listSaleAmount + taxAmount;
return saleTotal;
}
public String 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);
}
public static double changeTaxAmount (double taxRate) {
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;
return taxRate;
}
public static double changeSaleRate (double saleRate) {
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;
return saleRate;
}
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
public static String printSaleRate; {
System.out.println("The Sale Rate is" + saleRate + ".");
}
}
TestCustomer class
import java.math.BigDecimal;
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);
Double totalOfAllSales = 0.00;
//I have no clue how to actually use the methods I created in the Customer class!
//These are my best guesses, which are obviously wrong
//Any help here would be greatly appreciated!
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
System.out.println("The total of all sales is $" + totalOfAllSales);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
You seem to be confused about the syntax for calling a method. The syntax is as follows:
object.method(arguments)
If there are no arguments it looks like this:
object.method()
Also, you need to use accessor and mutator methods instead of directly setting instance variables like you do here:
customer1.listSaleAmount = 65.00;
You should implement methods like these:
public void setListSaleAmount(double lsa) {
listSaleAmout = lsa;
}
public double getListSaleAmount() {
return listSaleAmount;
}
and make listSaleAmount private.
Problem #2: The syntax for defining the methods. You are using this code to define a method:
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
You should be using this code:
public static String printTaxRate() {
System.out.println("Tax Rate is" + taxRate + "%.");
}
The problem is the weirdly placed semicolon inside the method header.

How do I write a method to calculate total cost for all items in an array?

I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}

Categories