• Post Reply Bookmark Topic Watch Topic
  • New Topic

Scope issues  RSS feed

 
Avery Jenkins
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I'm working through the MIT OpenCourseware materials, and working on a program to calculate pay to hourly employees. There are several rules that apply to this program, which you will probably see (hopefully) in the code.



My problem is that the variable totalPay cannot be resolved to a variable. I know from a previous issue I had that I really can't declare variables inside an if statement. On the other hand, I don't want to put it in line 4 because I don't have numbers to assign to it. I know its a scope issue, just not sure where to place the global variable (or if that's even possible.) Any hints you can give would be awesome.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avery,
I would declare it at the beginning of the compute method. You can initialize it to zero. Which is a logical default.

If you declare it in the if statement, you can't refer to it outside of the if statement. You want the variable to be as local as possible. The if statement is too local. An instance/global variable is too broad. In the method is just right.

Another alternative is to leave it in the if statement and not refer to it in the else. After all, you don't really have a total there.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!