简体   繁体   中英

StackOverFlow Error on line of code

I am taking a programming class and set up code about computing a paycheck. Everything works fine except for line 11. I end up getting a stackoverflow error.

However when I remove this line of code

double weeksWages = pay(50, 10); // weeksWages is 550

The error goes away, but when running program, I end up with 10 instead of 550 that is intended. This is probably really simple to fix, but not sure. Thanks!

Here is the full code:

import java.util.Scanner;
import static java.lang.System.out;

public class ComputePayCheck {    

  static Scanner in = new Scanner(System.in);


  public static double pay(int hours, double hourlyRate) {
     int otHours = (hours > 40) ? hours - 40 : 0;
     double weeksWages = pay(50, 10); // weeksWages is 550
     return otHours;
  }

  public static void main(String[] args) {
     out.print("Enter hours worked: ");
     int hours = in.nextInt();
     out.print("Enter hourly rate: ");
     double hourlyRate = in.nextDouble();
     out.print("Week's Salary is: " + pay(hours, hourlyRate));


  }

}

You're getting a stack overflow because your pay function is recursively calling itself with no end in sight. I'm not sure what the exact expected behaviour of your method is, but try something like this instead.

public static double pay(int hours, double hourlyRate) {
 int otHours = (hours > 40) ? hours - 40 : 0;
 return hourlyRate * otHours;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM