Duane Duane - 4 months ago 19
Java Question

Check if a String contains numbers Java

I'm writing a program where the user enters a String in the following format:

"What is the square of 10?"

  1. I need to check that there is a number in the String

  2. and then extract just the number.

  3. If i use
    , the program can't find a number in the String, no matter what the input is, but
    will only work when there is only numbers.

What can I use as a solution for finding and extracting?


The solution I went with looks like this:

    Pattern numberPat = Pattern.compile("\\d+");
    Matcher matcher1 = numberPat.matcher(line);

    Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
    Matcher matcher2 = stringPat.matcher(line);

    if (matcher2.find())

        if (matcher1.find())
            int number = Integer.parseInt(matcher1.group());

            pw.println(number + " squared = " + (number * number));

I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)