Method not calculating properly

No, a void would mean it doesn't return anything, it will still be returning the result of your calculation. You shouldn't be assigning to a variable in your return statement. Either assign to a variable and then return it, or just return the result of the calculation directly.

Ok cheers for replying, I did what what you said

Code:
public double TaxCalculator(double TotalWage,double HighTaxRate)
 {
     return  TotalWage * HighTaxRate;
 }

but its still printing out the answer as 0 :confused:

Code:
 System.out.println("The amount of tax you pay weekly is: " +a3.TaxCalculator(a3.TotalWage,a3.HighTaxRate));
 
You are still passing in parameters to your function instead of using your class model. If your are creating an instance of your Customer object and assigning values to that, then you should be using those properties in your function calculations.

It looks like your WeeklyWage function is supposed to calculate the total wage, so you should be calling that function so that you have a value to use as your total wage in your tax calculation.
 
planty is right and you wouldn't write code like you have.

Ignoring that for the moment you need to do be doing something with the return values in addition to just printing them.

For example:-

Code:
a3.TotalTaxPayed = a3.TaxCalculator(a3.TotalWage, a3.HighTaxRate);
System.out.println("The amount of tax you pay weekly is: " + a3.TotalTaxPayed);


You've then got your output and also have the value saved.
 
Basically what planty said.

A very rough example:-

Code:
public class Customer
{
    protected double Wage;
    protected double TaxRate;

    public double CalculateTax()
    {
         return Wage * TaxRate;
    }
}
 
It's been a while since I did some Java so I decided to have a dabble.

There are a couple of ways to restructure the classes. I'll show one of the ways and then also describe the other. It's important to understand a few concepts; it's important to know the difference between class variables and method variables (I forget their proper names, it's been a while since I did any serious Java development). In my example I've deliberately called the variables in the Customer class the same thing. But you can see where class variables are used because they are prefixed with "this.".

FIRST WAY

In my example I've tried to keep fairly close to your structure by using getter and setter methods. What this means is that I've made the Customer class variables to be scoped as private. So no other classes can refer to them directly. Instead the only way to get them, or to set them, is to use the getter and setter methods. I feel this is generally safer than allowing other classes to access the variables directly because this way the Customer class has complete control over how valkues are accessed or referenced. The only way to change them or to retrieve them is to use the Customer class itself.

1) The Acccountancy class instantiates a Customer object.
2) The Accountancy class then uses the Customer class setter methods to set all of the customer data.
3) When the Accountancy class wants to retrieve those values again it uses the getter methods.
4) Several variables are calculated and not stired directly. There are specific methods to retrieve them (I called them all calculateXXXXX). I don't store them in variables, but calculate them every time, because it's possible that the variables which the calculation methods depend on could be changed at any time via a setter method.

Customer Class:
Code:
public class Customer {

    private String customerName;
    private double openingBalance;
    private double debitPurchases;
    private double creditPayment;
    private double closingBalance;
    private double hoursWorked;
    private double hourlyRate;
    private double totalWage;
    private double highTaxRate;
    private double totalTaxPaid;


    //
    // Getters and setters - These are pairs of methods used to get or set private variables
    //

    public String getCustomerName() {
        return this.customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public double getOpeningBalance() {
        return this.openingBalance;
    }

    public void setOpeningBalance(double openingBalance) {
        this.openingBalance = openingBalance;
    }

    public double getDebitPurchases() {
        return this.debitPurchases;
    }

    public void setDebitPurchases(double debitPurchases) {
        this.debitPurchases = debitPurchases;
    }

    public double getCreditPayment() {
        return this.creditPayment;
    }

    public void setCreditPayment(double creditPayment) {
        this.creditPayment = creditPayment;
    }

    public double getClosingBalance() {
        return this.closingBalance;
    }

    public void setClosingBalance(double closingBalance) {
        this.closingBalance = closingBalance;
    }

    public double getHoursWorked() {
        return this.hoursWorked;
    }

    public void setHoursWorked(double hoursWorked) {
        this.hoursWorked = hoursWorked;
    }

    public double getHourlyRate() {
        return this.hourlyRate;
    }

    public void setHourlyRate(double hourlyRate) {
        this.hourlyRate = hourlyRate;
    }

    public double getTotalWage() {
        return this.totalWage;
    }

    public void setTotalWage(double totalWage) {
        this.totalWage = totalWage;
    }

    public double getHighTaxRate() {
        return this.highTaxRate;
    }

    public void setHighTaxRate(double highTaxRate) {
        this.highTaxRate = highTaxRate;
    }

    public double getTotalTaxPaid() {
        return this.totalTaxPaid;
    }

    public void setTotalTaxPayed(double totalTaxPaid) {
        this.totalTaxPaid = totalTaxPaid;
    }


    //
    //  Methods to return calculated values
    //

    public double calculateCustomerBalance() {
        return this.openingBalance + this.creditPayment - this.debitPurchases;

    }

    public double calculateWeeklyWage() {
        return this.hoursWorked * this.hourlyRate;

    }

    public double calculateTax() {
        return calculateWeeklyWage() * this.highTaxRate;
    }

}


Accountancy Class:
Code:
public class Accountancy {


    public static void main(String[] args) {

        Customer a3 = new Customer();

        a3.setCustomerName("David OSullivan");
        a3.setOpeningBalance(700);
        a3.setDebitPurchases(500);
        a3.setCreditPayment(100);
        a3.setClosingBalance(0);
        a3.setHoursWorked(65.4);
        a3.setHourlyRate(15.0);
        a3.setHighTaxRate(42.0);

        System.out.println("Your name is: " + a3.getCustomerName());
        System.out.println("Your opening Balance is: " + a3.getOpeningBalance());
        System.out.println("Your Closing Balance is: " + a3.calculateCustomerBalance());
        System.out.println("This week you worked: " + a3.getHoursWorked());
        System.out.println("Your Hourly Rate is: " + a3.getHourlyRate());
        System.out.println("You pay the tax rate of 42%!");

        System.out.println("Your total wage this week is: " + a3.calculateWeeklyWage());
        System.out.println("The amount of tax you pay weekly is: " + a3.calculateTax());

        System.out.println();

    }

}


SECOND WAY

Another way of doing it would be to have a constructor where you pass all data into it. When the object is created all of the class variables are assigned within this constructor. You then don't need setter methods because you've already set the values when the object was created. You would still need some of the getter methods, or to expose the class variables directly again (public or protected). The slight disadvantage of this approach would be that once you've created the Customer object then you can't ever change the values in it nless you create a new object.

Of course it would be possible to do both; allow the values to be set by the constructor and also create every setter method. This way you would have a choice of which way you want to set the values.
 
Having a problem here in that it gets as far as asking how old your child is and how many kids you have but it won't do the calculation,it just bypasses it and loops around asking you pick another selection, any idea? thanks.

Code:
         Menu();
      
        System.out.println("Your child benefit is: " +ChildBenefit());
    } 
      
        public static void Menu()
        {
      
        int Choice;
        do
        {
          
            Scanner sc = new Scanner(System.in);
          
            System.out.println("Please Pick an option by pressing 1,2,3 or 0 to Exit the program");
            Choice = sc.nextInt();
          
            switch(Choice)
            {
            case 1:
            ChildBenefit();
            break;
          
            case 2:
            WaterCharges();
            break;
          
            case 3:
            ElectricalCharges();
            break;
          
            case 0:
            System.out.println("Thank you and goodbye!");
            break;
          
            default:
                System.out.println("Not a vaild selection!");
                break;
            }
      
            }while(Choice != 0);
        
        }
  

  
    public static double ChildBenefit()
    {
       int Number_Of_Children;
       int ChildAge;
    
       Scanner sc = new Scanner(System.in);
       System.out.println("Please enter the age of your child: ");
       ChildAge = sc.nextInt();
    
       if(ChildAge <= 18)
       {
           System.out.println("Please enter the number of Children you have: ");
           Number_Of_Children = sc.nextInt();
           double result = Number_Of_Children * 27.60;
           return result;
       }
        else
           {
            System.out.println("The age of the person entered is over the limit and thus receive no benefits!");
            return 0;
           }
       }
    
  
  
    public static void WaterCharges()
    {
        System.out.println();
    }
  
    public static void ElectricalCharges()
    {
        System.out.println();
    }
 
Your program will never reach

Code:
System.out.println("Your child benefit is: " +ChildBenefit());


Until you quit the menu with your zero option.

At that point everything you've previously entered is throw away and you've got an unrelated call to ChildBenefit().
 
You probably want something like this (still **** code):

Code:
        Menu();
    }
   
    public static void Menu()
    {
   
        int Choice;

        do
        {
            Scanner sc = new Scanner(System.in);
       
            System.out.println("Please Pick an option by pressing 1,2,3 or 0 to Exit the program");
            Choice = sc.nextInt();
       
            switch(Choice)
            {
            case 1:
                System.out.println("Your child benefit is: " + ChildBenefit());
                break;
 
SNIP


If you have a method that returns a value and you don't use the return value immediately, or deliberately store it somewhere for later, then it has gone.
 
You probably want something like this (still **** code):

Code:
        Menu();
    }
 
    public static void Menu()
    {
 
        int Choice;

        do
        {
            Scanner sc = new Scanner(System.in);
     
            System.out.println("Please Pick an option by pressing 1,2,3 or 0 to Exit the program");
            Choice = sc.nextInt();
     
            switch(Choice)
            {
            case 1:
                System.out.println("Your child benefit is: " + ChildBenefit());
                break;
 
SNIP


If you have a method that returns a value and you don't use the return value immediately, or deliberately store it somewhere for later, then it has gone.

I tried it your way before posting and it wouldn't work, a red line appeared underneath the system.out.println line.
 
It was just a quick cut-n-paste of a part of your code to suggest a slightly more sensible structure.

If the IDE is showing an error isn't it telling you what it thinks is wrong?
 
It was just a quick cut-n-paste of a part of your code to suggest a slightly more sensible structure.

If the IDE is showing an error isn't it telling you what it thinks is wrong?

I've become a lot better at understanding errors when they happen thankfully.


The below code is suppose to return true or false if the number entered is within a certain range, its not printing out the true or false though and I can't understand why.

Code:
public static void main(String[] args) {
        
        new MinValue().rangeTest(0,1,100);

    }

    private boolean rangeTest(int val,int low,int high)
    {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("PLEASE ENTER A NUMBER:");
        val = sc.nextInt();
        
        if(val > low  && val < high)
        {
            return true;
        }
        else
            return false;


Any ideas?
 
You have a function that nominally returns a boolean value.

You aren't capturing the return value (true/false), and you certainly aren't doing anything to output it.

If you call a function that returns something you're usually going to have some sort of assignment:
Code:
bool valueReturned = MyFunction();
//now do something with the return value

private boolean MyFunction()
{
    return false;
}
 
You have a function that nominally returns a boolean value.

You aren't capturing the return value (true/false), and you certainly aren't doing anything to output it.

I got it working but only because I changed it to static method.....


Code:
Scanner sc = new Scanner(System.in);
            
         int val = 0;
         int Low = 1;
         int High = 100;
        
        
        System.out.println("PLEASE ENTER A NUMBER:");
        val = sc.nextInt();
        
        if(rangeTest(val,Low,High))
        {
            System.out.println("This is true");
        }
        else
        {
            System.out.println("THIS IS FALSE");
        }
    
    
    }

    public static boolean rangeTest(int value,int low,int high)
    {
        
        
        if(value > low  && value < high)
        {
            return true;
        }
        else
        {
            return false;
        }
 
It's working because you've completely changed the structure to something that makes sense. The change to static is trivial.
  • The rangeTest function now does what you'd expect, accept values and return a value based on them.
  • You're doing something with the return value.
  • You now have code to create some output.
  • Your input code is located where it's actually useful.
 
Back
Top Bottom