• Post Reply Bookmark Topic Watch Topic
  • New Topic

Adding the integers of a number  RSS feed

 
irish kelly
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have to write the java for the following; the user enters a number and the integers of that number are added together, for example I enter "234" and the programs produces "2+3+4=9" .

've done the code but I have a problem.... instead of adding all the integers and returning the answer, the program instead returns the last intetger as the answer.

 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The same question has already been asked here.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since this is a new question (which seems unrelated to the original question in the topic where irish kelly posted it first), let's continue with this question here. I've closed the other topic.

Note that Punit Jain gave you a hint about what might be wrong: carefully look at the condition for the while loop in line 11: while (number >= 100) - is that what you intended? Suppose the user enters 234, then what is the program going to do exactly? Trace the steps the program will take - that will make it clear why it doesn't do what you think it should do.
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger and Punit Jain have provided some useful answers to this question in the old topic. Any chance to move those responses here?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger wrote:
all programming is done the same way. You break the problem down into very simple parts, and work on ONE at a time.

For example, This program requires you to to at LEAST four things:

1) Get input from a user
2) convert a number into into individual digits.
3) Sum a bunch of numbers
4) print out a number

It is key to realize that each and every one of those can - and more importantly should - be done separately from the others.

So, work on one at a time. Only when you have gotten whichever one you do first to work should you start to think about working on the second.

Punit Jain wrote:

while (number >=100)
{
counter=number%10;
sum = sum+counter;
number=number/10;
}

Trace your code and check your condition in while loop.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!