• Post Reply Bookmark Topic Watch Topic
  • New Topic

Another beginner problem...  RSS feed

 
Tod Novak
Greenhorn
Posts: 13
MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So...here's the exercise I'm working on:

Write a program that adds up integers that the user enters. First the programs asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum.

How many integers will be added:
5
Enter an integer:
3
Enter an integer:
4
Enter an integer:
-4
Enter an integer:
-3
Enter an integer:
7

The sum is 7

Be careful not to add the number of integers (in the example, 5) into the sum.


This is what I've come up with so far:


My issue is trying to figure out how to store, then add the integers that are input by the user.

I know this is very basic, and maybe it's because I've been working all day and trying to figure this out afterwards and my brain is fried, but I just can't seem to get the logic down.

I promise, one day I'll get this stuff down and can actually contribute help instead of asking for it.
 
Robert Richardson
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int total = 0;

total = total + num;

System.out.println("Total is " + total);

I'll leave it to you to insert the code in your program.
Cheers
Robert
 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of

int sum;

give num an initial value, like this

int sum = 0;

Because before you do any adding, your total is zero. Then after your num=scan.nextInt(); line, just add this:

sum = sum + num;

That takes the current value of sum, adds the value of num, and makes that total number to be the value of sum.
So if you have the numbers 2,4, and 6, sum changes like this:

sum = 0;
sum = 0 + 2;
sum = 2 + 4;
sum = 6 + 6;

Then later, you want to calculate the average, which means you divide by the number of integers entered, so just make sure you don't make the computer divide by 0.
 
Tod Novak
Greenhorn
Posts: 13
MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both for the help. Just needed a push in the right direction.

Appreciate it!

Edit: I've made the suggested changes and all is working as intended.

Thanks again
[ May 21, 2008: Message edited by: Tod Novak ]
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done, but please use a more informative title for your threads; people don't know what "Another beginner problem" means when they go through the list of threads.

Please, members, be careful about posting too much code as an answer; the people asking the questions learn better if you give them hints and they work them out for themselves.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!