0

So I have to write a program for an invoice where I define the variables locally, instead of globally. So it kinda looks like this the way I have it.

public void setAmount(int anyAmount)
{ 
int amount;
amount = anyAmount;
}

I then do the display method like this and get an error saying cannot find symbol

public void displayInvoice()
{
System.out.println("Amount: " + amount);

I can easily do this globally, but having troubles with this. Thank you!

11
  • 2
    Are you sure you read the task correctly? Commented Feb 26, 2013 at 21:41
  • 3
    you should declare amount as class level variable and then set it and get its resuls Commented Feb 26, 2013 at 21:41
  • Is the requirement that variables be defined locally part of a homework assignment? Commented Feb 26, 2013 at 21:42
  • @nsgulliver isn't that as global as it gets in Java? Commented Feb 26, 2013 at 21:42
  • It is for an assignment, for some reason he wants us to do it locally instead. We have done others with a global variable, but I guess not this time. The actually question in the book does not care, but during the instructions he added saying not to define globallly Commented Feb 26, 2013 at 21:42

2 Answers 2

3

When you declare a variable inside a function, such as in your setAmount, it only exists for as long as that function is executing; it only exists between the { and }. That's why you're unable to reference it later in the second function, as it no longer exists. Essentially, what you're doing is setting it, and then getting rid of it right away, through no effort on your code, but simply through the way memory is allocated and used in programs.

The way to get around this would be to use a "global" as you've said, or to pass it back after you set it, and put it into another variable, which you then send to your displayInvoice function. The last method requires that the setAmount and displayInvoice are part of a larger function themselves, and the intermediary variable is declared inside it. Over all, a "global" as you've said, is the easiest and probably best solution given what you've explained.

Unworking Example:

main() {
   int amount = 0;
   amount = setAmount(5);
   displayInvoice(amount);
}

In doing so though, you may as well forgo the setAmount function, as you can see it's fairly redundant. Keeping set amount, you'd need to change it to

Public int setAmount(int anyAmount)
Sign up to request clarification or add additional context in comments.

Comments

0

When you declare a variable inside a method it becomes local meaning it's only visible in that method, that is why you are getting that error, you can correct that by making it global.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.