The code I wrote compiles well, but there are certain values that do not calculate. The rate and hours value, tuition and .08 do not calculate. Maybe my code is wrong or something. I am still new to java so i am trying my best. Here is my code:
import java.io.*;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Tuition
{
static double fees;
static double rate;
static double tuition;
private static Scanner sc;
public static void main(String[] args) throws IOException
{
//declare variables
int hours;
//call methods
displayWelcome();
hours = getHours();
rate = getRate(hours);
tuition = calcTuition(hours, rate);
fees = calcFees(tuition);
}
public static void displayWelcome()
{
//welcome statement
System.out.println("Welcome to school that offers distance learning courses");
}
public static int getHours()
{
//declare method variables
int hours = 0;
//a user must enter a string value
System.out.println("Enter total number of hours");
sc = new Scanner(System.in);
try
{
hours = sc.nextInt();
}
catch(NumberFormatException e)
{
System.out.print("Incorrect number");
}
return hours;
}
public static double getRate(int hours)
{
if (hours > 15)
{
System.out.println("rate per credit hour is 44.50");
}
else
{
System.out.println("rate per credit hour is 50.00");
}
return rate;
}
public static double calcTuition(int hours, double rate)
{
tuition =(double)rate * hours;
System.out.print("tuition is" + (tuition));
return tuition;
}
public static double calcFees(double tuition)
{
fees =(double)tuition * .08;
System.out.print("fees are" + (fees));
return fees;
}
public static void displayToatal(double total)
{
DecimalFormat twoDigits = new DecimalFormat("$#,000.00");
System.out.println("the total value is"+ twoDigits.format(tuition + fees));
}
}
In calcTuition()
tuition =(double)rate * hours;
should be
tuition =rate * (double)hours;
: )
You aren't setting the rate. You need a line of code that looks like "rate = x;". You only have println's in the getRate method, but you don't actually set the variable to equal anything.
Related
I want to do an operation for calculating Body Mass Index in my CalBMI method, which depends on the inputs for CalWt and CalHt methods. Then the CalBMI method will return a BMI answer. How can I do such operation?The operation in my CalBMI
import java.util.*;
public class PracticeMethods_returningValues {
static Scanner type=new Scanner(System.in);
public static void main(String[] args)
{
double Wt=0, Ht=0, BMI;
System.out.println("Your Weight in Kg is: " + CalWt(Wt) );
System.out.println("Your Height in meters is: " + CalHt(Ht) );
System.out.println("Your BMI is: " + CalBMI(Wt,Ht) );
}
public static double CalWt(double a){
System.out.println("Please enter your Weight in lbs: ");
double Wt=(type.nextDouble() * .454); //Converts to Kg.
return Wt;
}
public static double CalHt(double b){
System.out.println("\nPlease enter your Height in inches: ");
double Ht=(type.nextDouble() * .025); //Converts to m.
return Ht;
}
public static double CalBMI(double a, double b){
double BMI=a/(Math.pow(b, 2));
return BMI;
}
}
Please tell me if the formula is wrong
public class BMI {
public static double CalWt(Scanner type) {
System.out.println("Please enter your Weight in lbs: ");
return type.nextDouble() * .45359;
}
public static double CalHt(Scanner type) {
System.out.println("Please enter your Height in inches: ");
return type.nextDouble()* .025;
}
public static double CalBMI() {
Scanner type = new Scanner(System.in);
return CalWt(type) / Math.pow(CalHt(type),2);
}
public static void main(String[] args) {
System.out.println(CalBMI());
}
}
I'm having a problem which I cannot fathom why. I have program I'm making where it takes a few inputs and calculates pay, tax, and final pay.
Everything is working except the final pay.
this calculates the final pay
import java.util.*;
public class Payroll extends Pay
{
public double calc_payroll()
{
super.calc_payroll();
super.tax();
netPay = grossPay - (grossPay * (tax/100));
return netPay;
}
}
this calculates pay and tax
import java.util.*;
public class Pay
{
private float hoursWrkd;
private float rate;
private int hoursStr;
float grossPay;
int tax;
float netPay;
public double calc_payroll()
{
grossPay = getHoursWrkd()*getRate();
return grossPay;
}
public double tax()
{
if (grossPay <= 399.99)
{
tax = 7;
}
else if (grossPay >= 400.00 && grossPay <= 899.99)
{
tax = 11;
}
else if (grossPay <= 900.00)
{
tax = 15;
}
return tax;
}
//Get & Set for hours worked
public float getHoursWrkd()
{
return hoursWrkd;
}
public void setHoursWrkd(float hoursWrkd)
{
this.hoursWrkd = hoursWrkd;
}
//Get & Set for Rate
public float getRate()
{
return rate;
}
public void setRate(float rate) {
this.rate = rate;
}
//Get & Set for hours straight
public int getHoursStr()
{
return hoursStr;
}
public void setHoursStr(int hoursStr)
{
this.hoursStr = hoursStr;
}
}
and this displays all
public class CalPayroll extends Pay
{
public void displayInfo()
{
super.calc_payroll();
super.tax();
Payroll colio = new Payroll();
colio.calc_payroll();
NumberFormat dollars = NumberFormat.getCurrencyInstance();
System.out.println("Gross Pay is : " + dollars.format(grossPay));
System.out.println("Tax is : " + tax + "%");
System.out.println("Net Pay is : " + dollars.format(netPay));
}
i have more files but those are the ones that just take the input, and call the other files.
The math is correct, however when i try to call the netPay variable and format it, it dosn't display any ammount. With grosspay it works. However my teacher said were supposed to pass grosspay into tax so it can use it, im not sure if that would fix it.
PLease help.
You try to display the netPay from CalPayroll, but this class never computes this value. When you do
Payroll colio = new Payroll();
colio.calc_payroll();
You’re probably expecting the netPay to be calculated in CalPayrool, but you’re actually calculating a separate value in a separate object, which has no effect on the current object.
I know that in method headers you aren't supposed to end it with a semicolon; however, all my method headers display the same error: ; expected. This is for the end of the header as well as between two parameters. How would I fix this?
import java.util.Scanner;
import java.text.DecimalFormat;
// This program will calculate the cost of someone's order at a coffee shop with applied possible discounts and tax
public class CoffeeShopWithMethods
{
public static void main (String [] args)
{
double cost = 0;
double discount = 0;
// Scanner allows user to enter values
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("\nEnter your username: ");
username = user_input.next( );
System.out.print ("\nWelcome to Casey's Classic Coffee, " + username + "! \n");
//call methods
displayMenu();
displayOutput(cost, discount, Discounted_cost, tax, Total_cost);
System.out.println("\nThank you " + username + "! Have a nice day!");
}
//outputs the menu to the screen
public static void displayMenu()
{
System.out.println ("\n\tItem\t\tCost\n\t1. Coffee\t$1.50\n\t2. Latte\t$3.50\n\t3. Cappuccino\t$3.25\n\t4. Espresso\t$2.00");
}
//prompts the user to enter item number, returns user input
public static int getItemNumber(int number) //error: ; expected
{
int number;
Scanner number = new Scanner(System.in);
System.out.print ("\nPlease enter the desired item number: ");
number = user_input.nextInt();
return number;
}
//prompts user to enter quantity, returns user input
public static int getQuantity (int quantity) //error: ; expected
{
System.out.print ("\nPlease enter the quantity: ");
quantity = user_input.nextInt();
return quanity;
}
//takes the item number and quantity and returns the subtotal
public static double computeSubTotal (double cost) //error: ; expected
{
int number = getItemNumber(number);
int quantity = getQuantity(quantity);
// Used final double in order to make coffee shop items constant
final double COFFEE = 1.50;
final double LATTE = 3.50;
final double CAPPUCCINO = 3.25;
final double ESPRESSO = 2.00;
double cost = 0;
if (number == 1)
cost = quantity * COFFEE;
else if (number == 2)
cost = quantity * LATTE;
else if (number == 3)
cost = quantity * CAPPUCCINO;
else if (number == 4)
cost = quantity * ESPRESSO;
}
//takes the subtotal and returns true if the user earned a discount; otherwise, returns false
public static boolean discountCheck (double cost) //error: ; expected
{
boolean status;
if (cost >= 10)
{
status = true;
}
else if (cost < 10)
{
status = false;
}
return status;
}
//takes the subtotal and returns the dollar amount of the discount earned by the user
public static double computeDiscount (double cost, double discount) //error: ; expected
{
if (discountCheck() == true)
{
discount = cost * 0.10;
}
else if (discountCheck() != true)
{
discount = 0;
}
return discount;
}
//takes the subtotal and the discount amount and returns the price after the discount is applied
public static double computePriceAfterDiscount (double cost, double discount) //error: ; expected
{
double discount = 0;
double Discounted_cost = 0;
Discounted_cost = cost - discount;
return Discounted_cost;
}
//takes the prices after the discount is applied and tax rate and returns the tax amount
public static double computeTax(double Discounted_cost) //error: ; expected
{
tax = Discounted_cost * 0.07;
return tax;
}
//takes the price after the discount is applied and the tax amount and returns the final total
public static double computeTotal(double Discounted_cost, double tax) //says ; expected
{
Total_cost = Discounted_cost + tax;
return Total_cost;
}
//takes the subtotal, discount amount, price after discount, tax, and final total and displays all the lines of output to the user
public static void displayOutput(double cost, double discount, double Discounted_cost, double tax, double Total_cost) //says ; expected at the end of method header
{
//call methods
double cost = computeSubTotal(cost);
double discount = computeDiscount(cost, discount);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf ("\nTotal before discount and tax: $%.2f\n ", cost);
System.out.printf("\nCalculated discount: $%.2f\n", discount);
System.out.printf("\nTotal after special discount: $%.2f\n", Discounted_cost);
System.out.printf("\nTax: $%.2f\n", tax);
System.out.printf ("\nTotal cost: $%.2f\n", Total_cost);
}
} //error:reached end of the file while parsing
1)You are using the variables with out declaring:
for eg: compare this snippet with your code snippet.
public static double computeTotal(double Discounted_cost, double tax)
{
double Total_cost = Discounted_cost + tax;
return Total_cost;
}
2)You are invoking undefined methods.
for eg:
you are calling discountCheck() but you have defined like this.
and you have not initialized local variables before using
public static boolean discountCheck (double cost){
boolean status;
if (cost >= 10)
{
status = true;
}
else if (cost < 10)
{
status = false;
}
return status;
}
in the above method status should be initialized.
3) You are declaring duplicate variables that are already available to the methods via parameters.
see the code defined by you here:
public static void displayOutput(double cost, double discount, double Discounted_cost, double tax, double Total_cost)
{
//call methods
double cost = computeSubTotal(cost);
double discount = computeDiscount(cost, discount);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf ("\nTotal before discount and tax: $%.2f\n ", cost);
System.out.printf("\nCalculated discount: $%.2f\n", discount);
System.out.printf("\nTotal after special discount: $%.2f\n", Discounted_cost);
System.out.printf("\nTax: $%.2f\n", tax);
System.out.printf ("\nTotal cost: $%.2f\n", Total_cost);
}
I would start by extracting your MenuItem(s) into an enum like,
static enum MenuItem {
COFFEE("Coffee", 1.5), LATTE("Latte", 3.5), CAPPUCINO("Cappuccino",
3.25), ESPRESSO("Espresso", 2);
MenuItem(String name, double cost) {
this.name = name;
this.cost = cost;
}
double cost;
String name;
public String toString() {
return String.format("%s $%.2f", name, cost);
}
}
Then your compiler errors were mainly due to declaring duplicate local variable names. I was able to fix the compiler errors and produce something that looks like what you want with,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = scan.nextLine();
System.out.printf("Welcome to Casey's Classic Coffee, %s!%n", username);
displayMenu();
displayOutput(scan);
System.out.printf("Thank you %s! Have a nice day!", username);
}
// outputs the menu to the screen
public static void displayMenu() {
MenuItem[] items = MenuItem.values();
for (int i = 0; i < items.length; i++) {
System.out.printf("%d %s%n", i + 1, items[i]);
}
}
public static int getItemNumber(Scanner scan) {
System.out.println("Please enter the desired item number: ");
return scan.nextInt();
}
public static int getQuantity(Scanner scan) {
System.out.println("Please enter the quantity: ");
return scan.nextInt();
}
public static double computeSubTotal(Scanner scan) {
int number = getItemNumber(scan);
int quantity = getQuantity(scan);
return quantity * MenuItem.values()[number - 1].cost;
}
public static boolean discountCheck(double cost) {
return (cost >= 10);
}
public static double computeDiscount(double cost) {
if (discountCheck(cost)) {
return cost * 0.10;
}
return 0;
}
public static double computePriceAfterDiscount(double cost, double discount) {
return cost - discount;
}
public static double computeTax(double Discounted_cost) {
return Discounted_cost * 0.07;
}
public static double computeTotal(double Discounted_cost, double tax) {
return Discounted_cost + tax;
}
public static void displayOutput(Scanner scan) {
double cost = computeSubTotal(scan);
double discount = computeDiscount(cost);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf("Total before discount and tax: $%.2f%n", cost);
System.out.printf("Calculated discount: $%.2f%n", discount);
System.out.printf("Total after special discount: $%.2f%n",
Discounted_cost);
System.out.printf("Tax: $%.2f%n", tax);
System.out.printf("Total cost: $%.2f%n", Total_cost);
}
Here is your entire code corrected and working: http://ideone.com/ta0R21
I really recommend redesigning this. I suggest making use of global variable in some instances.
like the Scanner object. Instead of initializing a new Scanner each method call, use a global
one to handle the entire job
I keep getting this error when I run this code and I do not know how to fix it. I've been doing Java for about 3 months now and could use some help. Basically the program asks the user to enter in the pay rate and the hours for each employee. Pay rate, hours and employee number are all arrays that are going to share the same index with each other. When the user enters in the pay rate and hours for the employee, the program returns the gross pay for that employee. Except this error keeps popping up. Please help!
Exception in thread "main" java.lang.NullPointerException
at chapter.pkg7.lab.Payroll.setPayRate(Payroll.java:41)
at chapter.pkg7.lab.Chapter7Lab.main(Chapter7Lab.java:45)
Java Result: 1
Here's the code:
package chapter.pkg7.lab;
import java.util.Scanner;
public class Chapter7Lab {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Payroll newEmployee = new Payroll();
int[] employeeNum = newEmployee.getEmployeeID();
double pay;
int hour;
for (int i = 0; i < employeeNum.length; i++)
{
System.out.println("Please enter the Pay Rate for Employee #" + employeeNum[i]);
pay = keyboard.nextDouble();
newEmployee.setPayRate(pay, i);
System.out.println("Please enter the hours for Employee #" + employeeNum[i]);
hour = keyboard.nextInt();
newEmployee.setHours(hour, i);
System.out.println("Gross pay is: " + newEmployee.getWages(i));
}
package chapter.pkg7.lab;
public class Payroll {
private int[] employeeID = new int[] {5658845, 4520125, 7895122,
8777541, 8451277, 1302850, 7580489};
private int[] hours;
private double[] payRate;
private double wages;
public double getWages(int index) {
wages = hours[index] * payRate[index];
return wages;
}
//Accessors and Mutators
public int[] getEmployeeID() {
return employeeID;
}
public void setEmployeeID(int[] employeeID) {
this.employeeID = employeeID;
}
public int[] getHours() {
return hours;
}
public void setHours(int hours, int index) {
this.hours[index] = hours;
}
public double[] getPayRate() {
return payRate;
}
public void setPayRate(double payRate, int index) {
this.payRate[index] = payRate;
}
}
You've declared payRate (and hours and wages) as arrays, but it's an uninitialized instance variable, so it's null.
Initialize it:
private double[] payRate = new double[employeeID.length];
(and likewise for hours and wages).
Add a constructor to your Payroll class that initialises the two arrays hours and payRate like this:
public Payroll(){
hours = new int[employeeID.length];
payRate = new double[employeeID.length];
}
Then when you create the Payroll object in your main class as you're currently doing with the line: Payroll newEmployee = new Payroll(); the arrays will be initialised.
NullPointerException
Arise when you won't initialize variable or object and try to access that varibale or object
I am having some issues with the following syntax.
I am currently learning Java and have been going through a past exam paper to help build my knowledge of Java.
Here is the question:
Write a class Account that has instance variables for the account number and current balance of the account. Implement a constructor and methods getAccountNumber(), getBalance(), debit(double amount) and credit(double amount). In your implementations of debit and credit, check that the specified amount is positive and that an overdraft would not be caused in the debit method. Return false in these cases. Otherwise, update the balance.
I have attempted to do this HOWEVER, I have not implemented the boolean functions for debit and credit methods. I just wanted to build the program first and attempt to get it working. I was going to look at this after as I was not sure how to return true or false whilst also trying to return an amount from the said methods.
Please forgive any errors in my code as I am still learning Java.
I can run my code, but when I enter deposit it does not seem to work correctly and I would appreciate any pointers here please.
Here is my code:
import java.util.*;
public class Account {
private int accountNumber;
private static double currentBalance;
private static double debit;
// ***** CONSTRUCTOR *****//
public Account(double currentBalance, int accountNumber) {
accountNumber = 12345;
currentBalance = 10000.00;
}
public int getAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
return accountNumber;
}
public double getcurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
return currentBalance;
}
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
public static void main(String [] args){
String withdraw = "Withdraw";
String deposit = "Deposit";
double amount;
Scanner in = new Scanner(System.in);
System.out.println("Are you withdrawing or depositing? ");
String userInput = in.nextLine();
if(userInput == withdraw)
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
if (userInput == deposit)
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
}
Again please forgive any errors in my code. I am still learning its syntax.
In the if-statement if(userInput == withdraw) you are attempting to compare String objects.
In Java to compare String objects the equals method is used instead of the comparison operator ==
if(userInput.equals(withdraw))
There are several instances in the code that compares String objects using == change these to use equals.
Also when using conditional blocks it is best to surround the block with braces {}
if(true){
}
You don't use brackets so only the first line after your if-statement gets executed. Also, String's should be compared using .equals(otherString). Like this:
if(userInput.equals(withdraw))
System.out.println("Enter amount to withdraw: "); //Only executed if userInput == withdraw
amount = in.nextDouble(); //Always executed
if(userInput.equals(withdraw)) {
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
//All executed
}
Do this:
if(userInput.equals(withdraw)) {
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
if (userInput.equals(deposit)) {
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
Note that if your amount to withdraw exceeds your current balance, you will get a 'warning message' but your withdrawal will continue. Thus you'll end up with a negative sum of money. If you don't want to do this, you have to change it accordingly. But, this way it shows how the use of brackets (or not using them) has different effects.
if (userInput == deposit)
should be
if (userInput.equals(deposit))
Same for withdrawal.
On these methods:
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
The inputs to the functions really shouldn't include the current balance, the object already knows what the current balance is (its being held in the objects currentBalance field, which as has been pointed out shouldn't be static).
Imagine a real cash machine that behaved like this:
Whats my current balance:
£100
CreditAccount("I promise my current balance is £1 Million, it really is", £10):
Balance:£1,000,010
Edit: Include code to behave like this
import java.util.*;
public class Account {
private int accountNumber;
private double currentBalance; //balance kept track of internally
// ***** CONSTRUCTOR *****//
public Account(int accountNumber, double currentBalance) {
this.accountNumber = accountNumber;
this.currentBalance = currentBalance;
}
public int getAccountNumber() {
return accountNumber;
}
public double getcurrentBalance() {
return currentBalance;
}
public boolean debit(double amount) {
//we just refer to the objects fields and they are changed
if (currentBalance<amount){
return false; //transaction rejected
}else{
currentBalance -= amount;
return true;
//transaction approaved and occured
}
//Note how I directly change currentBalance, there is no need to have it as either an input or an output
}
public void credit( double amount) {
//credits will always go through, no need for return boolean
currentBalance += amount;
//Note how I directly change currentBalance, there is no need to have it as either an input or an output
}
public static void main(String [] args){
Account acc=new Account(1234,1000);
acc.credit(100);
System.out.println("Current ballance is " + acc.getcurrentBalance());
boolean success=acc.debit(900); //there is enough funds, will succeed
System.out.println("Current ballance is " + acc.getcurrentBalance());
System.out.println("Transaction succeeded: " + success);
success=acc.debit(900); //will fail as not enough funds
System.out.println("Current ballance is " + acc.getcurrentBalance());
System.out.println("Transaction succeeded: " + success);
}
}
I've not bothered using the typed input because you seem to have the hang of that
Without '{' and '}' the first line after an if statement only gets executed as part of that statement. Also, your if (userInput == deposit) block isn't correctly indented, it shouldn't be under the if (userInput == withdraw). And string comparisons should be done using userInput.equals(withdraw)
For the debit and credit methods:
public static boolean debit(double currentBalance, double amount) {
currentBalance -= amount;
if<currentBalance < 0){
return false
}
return true;
}
public static boolean credit(double currentBalance, double amount) {
currentBalance += amount;
if<currentBalance > 0){
return false
}
return true;
}
Now I think I have the boolean values mixed up. The description is a little bit unclear on what to return for each method.
Use equals() method instead == which compares the equality of Objetcs rather values
import java.util.*;
public class Account{
private int accountNumber;
private static double currentBalance;
private static double debit;
// ***** CONSTRUCTOR *****//
public Account(double currentBalance, int accountNumber) {
accountNumber = 12345;
currentBalance = 10000.00;
}
public int getAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
return accountNumber;
}
public double getcurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
return currentBalance;
}
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
public static void main(String [] args){
String withdraw = "Withdraw";
String deposit = "Deposit";
double amount;
Scanner in = new Scanner(System.in);
System.out.println("Are you withdrawing or depositing? ");
String userInput = in.nextLine();
if(userInput.equals(withdraw))
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
if (userInput .equals(deposit))
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
}