7 Replies Latest reply on Aug 8, 2009 3:20 PM by 807588

    input numbers.. adding them

      hello i need to write a program to add numbers inputed... ex 234 = 9... (2+3+4).. how would i do this... is there a way to seperate each number in a input to add seperatly?... any thoughts let me know... has to be recurssive methods.. no loops.. thanks
        • 1. Re: input numbers.. adding them
          So what do you have, what have you tried, and what is giving you trouble?
          • 2. Re: input numbers.. adding them
            I guess it depends exactly what kind of calculator (that's what it sounds like, a calculator) is it? Is it a command prompt interface? Or is it like MSCalculator?
            • 3. Re: input numbers.. adding them
              javax.script.ScriptEngine, javax.script.ScriptEngineManager
              • 4. Re: input numbers.. adding them
                Caarmel wrote:
                javax.script.ScriptEngine, javax.script.ScriptEngineManager
                Hi Caarmel,

                The OP has an assignment to do. It is fruitless to suggest him/her an API he/she is not allowed to use.
                • 5. Re: input numbers.. adding them
                  First you have to read a line of text.
                  One way to do that is this
                  String input=System.console().readLine();
                  Then you need a way to get a single character from the input.
                  String firstCharacter=input.substring(0, 1);
                  That gives you the first character in the string.

                  Then you can simply convert that to an int like this
                  int number=Integer.parseInt(firstCharacter);
                  Another useful hint is that you can do this
                  String restOfString=input.substring(1);
                  This cuts of the first character and gives you the rest.

                  Now you just have to write a recursive method that takes a String as an argument and adds all the numbers by adding the first number to the sum of the rest.
                  • 6. Re: input numbers.. adding them
                    Hii rayman551
                    private void add()
                                int vlu = 234;
                                int dig = 0;
                                int Res  = 0;
                                String V = String.valueOf(vlu);
                                int len = V.length();
                                for(int i = 0; i < len; i++)
                                   dig = Integer.parseInt(String.valueOf(V.charAt(i)));
                                   Res = Res + dig;
                    i think this is the convenient way to solve... hope this can help..
                    • 7. Re: input numbers.. adding them
                      dev wrote:
                      hope this can help..
                      No, it won't help. The OP must not use loops in his/her assignment.