2

I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"

And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.

But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?

A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.

I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output

package reverseTest;

import java.util.Scanner;
public class ExtractNumbers {`enter code here`
      public static void main(String[] args) 
      {
          String str;
          String numbers;

          Scanner SC=new Scanner(System.in);

          System.out.print("Enter string that contains numbers: ");
          str=SC.nextLine();

          //extracting string
          numbers=str.replaceAll("[^0-9]", "");

          System.out.println("Numbers are: " + numbers);
      }
}

And this adds ALL the numbers in a string:

String a="jklmn489pjro635ops";

    int sum = 0;

    String num = "";

    for(int i = 0; i < a.length(); i++) {
        if(Character.isDigit(a.charAt(i))) {
            num = num + a.charAt(i);
        } else {
            if(!num.equals("")) {
                sum = sum + Integer.parseInt(num);
                num = "";
            }
        }
    }
    System.out.println(sum);
}

I don't know how to combine this code with code that can add the numbers this method outputs together.

5
  • 1
    when you do replaceAll with this regex you're also replacing the spaces with empty string so this string: "This 23 string has 738 numbers" will turn to: "23738" and you won't be able to know where the first number ended and the next begins. Don't replace the spaces as a first step, then split the string on spaces and parse each number separately. From there it should not be very difficult to achieve your goal. Commented May 26, 2019 at 4:00
  • 1
    Do you need some code to get the numbers in the text or do you need to know how to combine both codes? Commented May 26, 2019 at 4:09
  • show a minimized section of your code Commented May 26, 2019 at 4:13
  • I think the first bit of code extracts the numbers. I need code to take those numbers and add the digits of them together and return those values. Any help would be greatly appreciated. Commented May 26, 2019 at 4:16
  • Why don't you just turn the second bit of code into a function, and call it on your System input reading call of the first? Commented May 26, 2019 at 5:01

3 Answers 3

4

We can try using Java's regex engine with the pattern \d+. Then we can iterate each match character by character, and tally the sum.

String a = "This 23 string has 738 numbers";
String pattern = "\\d+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(a);
while (m.find()) {
    System.out.print("found numbers: " + m.group(0) + " = ");
    int sum = 0;
    for (int i=0; i < m.group(0).length(); ++i) {
        sum += m.group(0).charAt(i) - '0';
    }
    System.out.println(sum);
}

This prints:

found numbers: 23 = 5
found numbers: 738 = 18
Sign up to request clarification or add additional context in comments.

2 Comments

but he say:"A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12." so in "jklmn489pjro635ops" should return 21 and 14 no?
@DrPepper Thanks for pointing that out. I have updated my answer.
1

You can simply split the input string to have separated tokens and then split each token to have only digits:

String s = "This 23 string has 738 numbers";
String[] st = s.split(" ");
for (int i=0 ; i<st.length ; i++) {
    if (st[i].matches("[0-9]+")) {
        String[] c = st[i].split("(?=\\d)");
        int sum = 0;
        for(int j=0 ; j<c.length ; j++) {
            sum += Integer.parseInt(c[j]);
        }
        System.out.println(sum);

    }
}

the output is:

5
18

1 Comment

adfsadsfsddasdf
1

I'm re-learning Java after a two decade hiatus, and evaluating BlueJ at the same time for possible use in my classroom. This seemed like a great project to practice with, so thanks for the post! Here's my take on it, without the use of Regular Expressions.

Class FindDigits:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class FindDigits
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter string to analyze: ");
        String input = scan.nextLine();

        FindDigits fd = new FindDigits(input);
        System.out.println("Input: " + fd.getInput());
        List<NumberSum> results = fd.getSums();
        if (results.size() > 0)
        {
            for(NumberSum ns: results)
            {
                System.out.println("Number: " + ns.getNumber() + ", Sum: " + ns.getSum());
            }
        }
        else
        {
            System.out.println("No numbers found.");
        }
    }

    private String _input;
    public String getInput()
    {
        return _input;
    }

    public FindDigits(String input)
    {
        _input = input;
    }

    private List<String> getNumbers()
    {
        List<String> numbers = new ArrayList();
        String curNumber = "";
        for(Character c: getInput().toCharArray())
        {
            if(Character.isDigit(c))
            {
                curNumber = curNumber + c;
            }
            else
            {
                if (!curNumber.isEmpty())
                {
                    numbers.add(curNumber);
                    curNumber = "";
                }
            }
        }
        if (!curNumber.isEmpty())
        {
            numbers.add(curNumber);
        }
        return numbers;
    }

    public List<NumberSum> getSums()
    {
        List<NumberSum> sums = new ArrayList<NumberSum>();
        for(String number: getNumbers())
        {
            sums.add(new NumberSum(number));
        }
        return sums;
    }

}

Class NumberSum:

public class NumberSum
{

        private String _number;
        public String getNumber()
        {
            return _number;
        }

        public NumberSum(String number)
        {
            _number = number;
            for(char c: number.toCharArray())
            {
                if(!Character.isDigit(c))
                {
                    _number = "";
                    break;
                }
            }
        }

        public int getSum()
        {
            return sum(getNumber());
        }

        private int sum(String number)
        {
            if (!getNumber().isEmpty())
            {
                int total = 0;
                for(char c: number.toCharArray())
                {
                    total = total + Character.getNumericValue(c);
                }
                return total;
            }
            else
            {
                return -1;   
            }
        }

}

Output: enter image description here

3 Comments

Use ! .equals instead of != for String comparison.
@Robert Thanks! So, for example, !getNumber().equals("")? Gonna take awhile to go back and forth between Java and .Net without making mistakes.
@Robert Switched to using isEmpty() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.