• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Scope issues

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author & internet detective
Posts: 41878
909
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic