Separating an Integer

66 views Asked by At

My question is how do I separate the digits in an integer? Below is the code I have and everything is how I want it minus the fact that I can't get the digits in the integer to separate. When I input "12345" currently the program outputs "12345" and I would like it to separate the digits so the output would be 1 2 3 4 5.

import java.util.*;

public class SNHU_Practice
{
    public static void main(String args[])
   {

       Scanner console = new Scanner(System.in);

        String input = "";
        int sum = 0;

        System.out.println( "Please enter a number: " );
        input = console.next();

        int i = 0;

        while( i < input.length() )
        {
            char temp = input.charAt(i);
            sum += Character.getNumericValue(temp);
            i++;
        }

        System.out.println( "The number entered was " + input + ". The sum     of these digits is: " + sum + "." );

    }
}
2

There are 2 answers

0
Valentin Blokhin On

You can just write

input.replace("", " ").trim()

instead of input in System.out.println. E.g:

System.out.println( "The number entered was " + input.replace("", " ").trim() + ". The sum     of these digits is: " + sum + "." );
0
Ramesh Kumar On

I guess this is what you want.

    import java.util.*;

    public class SNHU_Practice{
         public static void main(String args[]){

   Scanner console = new Scanner(System.in);

    String input = "";
    StringBuilder result = new StringBuilder("");
    int sum = 0;

    System.out.println( "Please enter a number: " );
    input = console.next();

    int i = 0;

    while( i < input.length() )
    {
        char temp = input.charAt(i);
        result.append(temp + " ");
        i++;
    }

    System.out.println( "The number entered was " + input + ". The output string is " + result + "." );

}

}