oliver thomas
oliver thomas

Reputation: 63

Method being called twice?

I am trying to write a simple program that takes an inputed salary from a user and then outputs that salary + 200. When i put in the value it displays the quesion to input the salary again, and then after putting the number in again it seems to work. Any idea why?

package learning;

import java.util.Scanner;

public class SalaryReadIn {

Scanner scan = new Scanner(System.in);

public SalaryReadIn () {

}

public int getSalary () {

    int currentSalary;
    System.out.println("Enter your current salary: ");
    currentSalary = scan.nextInt();
    return currentSalary;

}

public void calculate () {

    int currentSalary = getSalary();
    int newSalary = currentSalary + 200;
    System.out.println("Your new salary is: £" + newSalary);

}

public static void main (String args[]) {

    SalaryReadIn salary = new SalaryReadIn();
    salary.getSalary();
    salary.calculate();

}


}

Thanks for any help!

Upvotes: 0

Views: 2214

Answers (2)

Roshana Pitigala
Roshana Pitigala

Reputation: 8806

As oliver has mentioned you are calling the getSalary() method twice.

  • JVM runs the main(String args[]) method at first.
  • Then it finds the line,

    salary.getSalary();
    
  • Then the JVM goes into getSalary() method and do whatever in there.

  • Next as it finds the salary.calculate() line, it goes into that method.
  • In your calculate() method, the line,

    int currentSalary = getSalary();
    

    contains the getSalary() method calling once again.


remove the following code line in the main method.

salary.getSalary();

Upvotes: 1

oliver thomas
oliver thomas

Reputation: 63

getSalary() was being executed twice as it is being called in the main method, and then being called in the second method that is being called.

Upvotes: 1

Related Questions