Results 1 to 3 of 3
  1. #1
    Julingo is offline Member
    Join Date
    Sep 2008
    Rep Power

    Default Calculate sum of long integer!


    Im 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 Im use to ada programminglanguage so I understand the problem but dont really know how to tackle the problem in java.

    So if someone could help I would be grateful!


  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Rep Power


    int n = longInteger;
    String s = String.valueOf(n);
    Use methods in the String class to get each digit to parse with Integer parseInt method.

  3. #3
    fishtoprecords's Avatar
    fishtoprecords is offline Senior Member
    Join Date
    Jun 2008
    Rep Power


    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

    Java 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

Similar Threads

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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts