Reputation: 422
Lets assume Num is simply 3.
public static int income(Scanner console, int number)
{
int incomeNum = console.nextInt();
int amount;
for(int i = 0; i <= number; i++)
{
System.out.println("Next income amount?");
incomeNum = console.nextInt();
amount += incomeNum;
}
return amount;
}
I need the incomeNum to add itself up when the user puts in a number and store it into amount and have that amount be returned to the main. I'm stuck because it says the amount is not initialized...
Upvotes: 1
Views: 511
Reputation: 250
"A local variable in Java is a variable that's declared within the body of a method. And in Java local variables don't have a default value (i.e. not even zero or null)." So if you use a local variable without first initializing it, the compiler will throw an error when trying to run the program.
The same happened with your local variable "amount
" and once you initialized it with amount = 0;
, now it works. Hope this clarifies the concept!
Upvotes: 1
Reputation: 346
You just need to give (amount) a value from the beginning.
int amount = 0;
everything else remains the same. Good luck.
Upvotes: 3
Reputation: 316
You have the right idea, but your problem is that you actually dont give int amount
a value.
Try int amount = 0;
Upvotes: 4