Results 1 to 2 of 2
  1. #1
    Emily is offline Member
    Join Date
    Jul 2007
    Posts
    5
    Rep Power
    0

    Question Breaking down an integer

    I am working on a project that involves a user entering a 9 digit number to be verified. To verify the number, all the digits have to be added together. At first I thought to use an array. But then it wouldn't be possibe to add the numbers if they all are in one cell. Is there a way to break the int down to single digits that can be added together?

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Java Code:
    public class Test {
        public static void main(String[] args) {
            int[] n = { 111111111, 111000000, 123454321 };
            for(int j =0; j < n.length; j++)
                System.out.println(n[j] + " total = " + addDigits(n[j]));
        }
    
        private static int addDigits(int n) {
            char[] chars = String.valueOf(n).toCharArray();
            int total = 0;
            for(int j = 0; j < chars.length; j++)
                total += Integer.parseInt(String.valueOf(chars[j]));
            return total;
        }
    }

Similar Threads

  1. Replies: 2
    Last Post: 02-18-2008, 04:24 AM
  2. Breaking from nested switch
    By javaplus in forum New To Java
    Replies: 3
    Last Post: 02-02-2008, 08:28 AM
  3. Short/Integer
    By mew in forum New To Java
    Replies: 3
    Last Post: 12-06-2007, 09:28 PM
  4. Integer vs int
    By bugger in forum New To Java
    Replies: 1
    Last Post: 11-14-2007, 09:13 PM
  5. Help with Integer in java
    By susan in forum New To Java
    Replies: 1
    Last Post: 07-14-2007, 05:25 AM

Posting Permissions

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