Java – How to split an Integer into an Array using Java

arraysintegerjava

I apologise if this has already been asked before, but I was unable to find a conclusive answer after some extensive searching, so I thought I would ask here. I am a beginner to Java (to coding, in general) and was tasked with writing a program that takes a user-inputted 3 digit number, and adds those three digits.

Note: I cannot use loops for this task, and the three digits must all be inputted at once.

String myInput;
    myInput =        
    JOptionPane.showInputDialog(null,"Hello, and welcome to the ThreeDigit program. "
    + "\nPlease input a three digit number below. \nThreeDigit will add those three numbers and     display their sum.");
    int threedigitinput;
    threedigitinput = Integer.parseInt(myInput);

Best Answer

There are a number of ways, one of which would be...

    String ss[] = "123".split("");
    int i = 
            Integer.parseInt(ss[0]) + 
            Integer.parseInt(ss[1]) + 
            Integer.parseInt(ss[2]);
    System.out.println(i);

another would be...

    String s = "123";
    int i = 
            Character.getNumericValue(s.charAt(0)) +
            Character.getNumericValue(s.charAt(1)) +
            Character.getNumericValue(s.charAt(2));
    System.out.println(i);

and still another would be...

    String s = "123";
    int i = 
            s.charAt(0) +
            s.charAt(1) +
            s.charAt(2) - 
            (3 * 48);
    System.out.println(i);

BUT hard coding for 3 numbers isn't very useful beyond this simple case. So how about recursion??

public static int addDigis(String s) {
        if(s.length() == 1)
            return s.charAt(0) - 48;
        return s.charAt(0) - 48 + addDigis(s.substring(1, s.length()));
}

Output for each example: 6