getDiscountedBill() will return final amount of the bill
if the bill is >2000, the bill receives a 15% discount
public class Discount
{
private double bill;
private double discount;
private double amt;
public static double getDiscountedBill(double bill)
{
if (bill > 2000)
{
discount = bill * .15;
amt = bill - discount;
}
return amt;
if (bill <= 2000)
{
return bill;
}
}
public void print()
{
System.out.println("Bill after discount :: ");
System.out.printf("%.2f\n", amt);
}
code in another main
public static void main( String args[] )
{
Scanner keyboard = new Scanner(System.in);
out.print("Enter the original bill amount :: ");
double amt = keyboard.nextDouble();
keyboard.getDiscountedBill(double);
keyboard.print();
error message:error: '.class' expected
keyboard.getDiscountedBill(double);
Change this statement:
keyboard.getDiscountedBill(double);
with this one:
double discuontedBill = getDiscountedBill(amt);
You're supposed to pass a value as a method argument, not to pass a type .
Related
I am getting an error that says: C:\Users\Jasmi\payroll\src\Payroll.java:68:38
java: variable grossPay might not have been initialized, but I am not sure how to fix it.
public class Payroll {
public String calculateGrossPay;
public String calculateNetPay;
private String name;
private int idNumber;
private double hourlyPayRate;
private double hoursworked;
Payroll(String nameGiven, int idNumbergiven) {
name = nameGiven;
idNumber = idNumbergiven;
hourlyPayRate = 7.15;
hoursworked = 0;
}
public String getName() {
return name;
}
public int getIDNumber() {
return idNumber;
}
public double getHourlyPayrate() {
return hourlyPayRate;
}
public double getHoursWorked() {
return hoursworked;
}
public void setName(String nameGiven) {
name = nameGiven;
}
public void setIDNumber(int idNumbergiven) {
idNumber = idNumbergiven;
}
public void setHourlyPayRate(double hourlypayrategiven) {
hourlyPayRate = hourlypayrategiven;
}
public void setHoursWorked(double hoursworkedgiven) {
hoursworked = hoursworkedgiven;
}
//gross pay plus overtime
public double calculateGrossPay() {
double overtime;
overtime = 0;
double grossPay;
if (hoursworked < 40) grossPay = hourlyPayRate * hoursworked;
else {
overtime = hoursworked - 40;
grossPay = (overtime * 1.5 * hourlyPayRate) + (40 * hourlyPayRate);
}
return grossPay;
}
//deductions
public double calculateNetPay() {
double netPay;
double grossPay;
double deduction = (.2579) * grossPay;
return netPay;
}
}
Here is the second document:
import javax.swing.JOptionPane;
public class PayrollClassTest {
public static void main(String[] args) {
String userInputString;
String userName;
int userId;
double userhourlyPayRate;
double userHoursworked;
userName = JOptionPane.showInputDialog("enter the name of this employee: ");
userInputString = JOptionPane.showInputDialog("Please enter employee ID: ");
userId = Integer.parseInt(userInputString);
userInputString = JOptionPane.showInputDialog("Please enter Hourly Pay Rate: ");
userhourlyPayRate = Double.parseDouble(userInputString);
userInputString = JOptionPane.showInputDialog("Enter the hours worked: ");
userHoursworked = Double.parseDouble(userInputString);
Payroll payroll1 = new Payroll(userName, userId);
payroll1.setHourlyPayRate(userhourlyPayRate);
payroll1.setHoursWorked(userHoursworked);
System.out.println(payroll1.getName() + " has a gross pay of " + payroll1.calculateGrossPay());
System.out.println(payroll1.getName() + " has a net pay of " + payroll1.calculateNetPay());
System.exit(0);
}
private static void calculateGrossPay() {
}
private static void calculateNetPay() {
}
}
I have tried to change deductions to be shown as this:
//deductions
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
}
It does work, but the results do not show the deductions:
Here is an example of the results:
Betty has a gross pay of 13000.0
Betty has a net pay of 0.0
Process finished with exit code 0
This is when I put name as Betty, gross pay as 100, and hours worked as 100. It shows the overtime correctly, but not the deductions.
Any help is greatly appreciated. thanks!
If my understanding of the code is correct then the following is where you are wrong for this piece of code.
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
First: netPay has no value assigned
This method will always return 0.
Reason : The netPay variable is declared and initialized to 0.
What you probably want to do before your return statement is perhaps;
netPay = grossPay - deduction;
I could be wrong in that logic, but I am definitely right when I say that you need to put some value to netPay before you return it.
Second: grossPay has no value assigned
In this method, you multiple .2579 with grossPay, but grossPay is 0 that you have now initialized.
You are assuming that the variable grossPay is shared for the two methods calculateGrossPay and calculateNetPay.
That is not true.
These are both two separate local variables that are declared separately in two different methods and have two different scopes.
You can read more about scope of java variables here:
variable docs from oracle
"in scope" meaning in java : StackOverflow question
My recommendation is to make grossPay a class variable instead of a method variable so that it could be shared between the two methods of the same class instance. (Assuming you are calling calculateGrossPay before calculateNetPay every time, so that grossPay can have the right value assigned to it.)
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
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.
I am getting an error that says one of the variables I have used are not initialized but upon reviewing the code I realize that I have in fact initialized the variable so I don't understand why I keep getting the error.
This is the error:
error: variable tax might not have been initialized
avgtax = (tax/sal)*100;
^
This is the code:
import java.util.*;
public class Taxable {
final static double first15=0.1;
final static double next20=0.2;
final static double over35=0.25;
final static double tax_inc=0.8;
public static void main(String[] args) {
double sal, TaxInc;
double tax, avgtax;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Salary: ");
sal = in.nextDouble();
TaxInc = sal*tax_inc;
if (TaxInc > 0 && TaxInc <= 15000)
tax = TaxInc*first15;
else if (TaxInc > 15000 && TaxInc <= 35000)
tax = (15000 * first15) + ((TaxInc - 15000) * next20);
else if (TaxInc > 35000)
tax = (15000 * first15) + (20000 * next20) + ((TaxInc - 35000) * over35);
else
System.out.printf("\nInvalid Salary Figure.");
avgtax = (tax/sal)*100;
System.out.printf("\nAt a salary of: %3.2f\nTax to be paid is:"
+ " %3.2f\nAverage Tax Rate is: %3.1f", sal, tax, avgtax);
}
}
Any help would be greatly appreciated.
This has some fixes to your code so it compiles and runs as expected
public class Taxable {
final static double first15=0.1;
final static double next20=0.2;
final static double over35=0.25;
final static double tax_inc=0.8;
public static void main(String[] args) {
double sal;
double taxInc;
double tax = 0;
double avgtax;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Salary: ");
sal = in.nextDouble();
taxInc = sal*tax_inc;
if (taxInc > 0 && taxInc <= 15000) tax = taxInc*first15;
else if (taxInc > 15000 && taxInc <= 35000) tax = (15000 * first15) + ((taxInc - 15000) * next20);
else if (taxInc > 35000) tax = (15000 * first15) + (20000 * next20) + ((taxInc - 35000) * over35);
else System.out.printf("\nInvalid Salary Figure.");
avgtax = (tax/sal)*100;
System.out.printf("\nAt a salary of: %3.2f\nTax to be paid is: %3.2f\nAverage Tax Rate is: %3.1f", sal, tax, avgtax);
}
}
However its not nicely structured ... I suggest reading Java naming convention and programming standards
EDIT:
Although you have accepted an answer, i suggest looking at this code sample, its written in slightly more readable way :)
import java.util.Scanner;
public class Taxable {
private final static double first15 =0.1;
private final static double next20 =0.2;
private final static double over35 =0.25;
private final static double tax_inc =0.8;
private double sal;
private double taxInc;
private double tax = 0;
private double avgtax;
public static void main(String[] args) {
System.out.printf("Enter Salary: ");
Scanner in = new Scanner(System.in);
Taxable taxable = new Taxable();
taxable.setSal(in.nextDouble());
System.out.println(taxable.calculateTax());
}
private String calculateTax(){
setTaxInc(getSal()*tax_inc);
if (getTaxInc() > 0 && getTaxInc() <= 15000){
setTax(getTaxInc()*first15);
}
else if (getTaxInc() > 15000 && getTaxInc() <= 35000){
setTax((15000 * first15) + ((getTax() - 15000) * next20));
}
else if (getTaxInc() > 35000){
setTax((15000 * first15) + (20000 * next20) + ((getTax() - 35000) * over35)) ;
}
else {
System.out.printf("\nInvalid Salary Figure.");
}
setAvgtax((getTax()/getSal())*100);
String calculation = "\n At a salary of: " + getSal() + "\n Tax to be paid is: " + getTax() + "\n Average Tax Rate is: " + getAvgtax();
return calculation;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public double getTaxInc() {
return taxInc;
}
public void setTaxInc(double taxInc) {
this.taxInc = taxInc;
}
public double getTax() {
return tax;
}
public void setTax(double tax) {
this.tax = tax;
}
public double getAvgtax() {
return avgtax;
}
public void setAvgtax(double avgtax) {
this.avgtax = avgtax;
}
}
Tax is not initialized and the error is due to the if loops.
If by any chance all if's fail, Tax will not get a value.
just put double Tax = 0;
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);
}
}