Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 09-09-2008, 10:11 PM
Member
 
Join Date: Sep 2008
Posts: 1
Rep Power: 0
Julingo is on a distinguished road
Default Calculate sum of long integer!
Hi!

I´m new to java and just started to learn but have a little problem. What I want to know is how I can get a long integer from the user and then caculate the sum of the separate numbers? I thinking I would use som sort of array and then calculate from there. The thing is I´m use to ada programminglanguage so I understand the problem but don´t really know how to tackle the problem in java.

So if someone could help I would be grateful!

//Viktor
Bookmark Post in Technorati
Reply With Quote
  #2 (permalink)  
Old 09-09-2008, 10:23 PM
hardwired's Avatar
Senior Member
 
Join Date: Jul 2007
Posts: 1,577
Rep Power: 4
hardwired is on a distinguished road
Default
int n = longInteger;
String s = String.valueOf(n);
Use methods in the String class to get each digit to parse with Integer parseInt method.
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 09-10-2008, 12:50 AM
fishtoprecords's Avatar
Senior Member
 
Join Date: Jun 2008
Posts: 571
Rep Power: 2
fishtoprecords is on a distinguished road
Post
If you are reading from the user, its already a String. No need to make it an Integer that you are not going to use.

With the string, you can just use a for loop to iterate through each character

Code:
long sum = 0;
for (int i=0; i < arg.length(); i++) {
   String  c = arg.substring(i,i);
   sum += Integer.valueOf(c);
}
This may not work, I typed it into the forum, not a compiler, but it should get you going. Debug on your own, its part of learning
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
calculate fft ram.west Advanced Java 2 08-27-2008 04:05 AM
how to post a long text in an editor bachtoutou New To Java 3 06-06-2008 03:00 AM
It takes very long time..... iresha Advanced Java 6 05-11-2008 03:31 AM
Error: convert from String to long bbq New To Java 1 06-29-2007 08:23 PM


All times are GMT +2. The time now is 03:45 AM.



VBulletin, Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org