0

I am trying to create a basic calculator program and I want to remove all non-numerical characters from the string input. (I am a java newbie). This is my current code:

package calculator;
import javax.swing.JOptionPane;
public class sub {

    public static void main(String[] args) {

        //Text & Input Box #1
        String input = JOptionPane.showInputDialog(null,
                "Input the first number",
                "Subtraction",
                JOptionPane.QUESTION_MESSAGE);

        //Input Box #2
        String input1 = JOptionPane.showInputDialog(null,
                "Input the second number",
                "Subtraction",
                JOptionPane.QUESTION_MESSAGE);

        //Data Collection
        int data1 = Integer.parseInt(input);
        int data2 = Integer.parseInt(input1);

        //Data Sum
        int sum = data1 - data2;

        //Output
        JOptionPane.showMessageDialog(null,  sum, "The Answer",         
JOptionPane.INFORMATION_MESSAGE);

    }
}
s_ofia
  • 117
  • 1
  • 10
  • 1
    `input1 = input1.replaceAll("\D", "");` – mr mcwolf Oct 08 '17 at 06:23
  • A possible duplicate of this issue - https://stackoverflow.com/questions/14974033/extract-digits-from-string-stringutils-java – kevenlolo Oct 08 '17 at 06:24
  • Multiple solutions... But do you want to let user input any value and then strip non numeric chars (which appears from your question) or do you want to restrict user to enter only numeric chars? – Optional Oct 08 '17 at 06:24
  • Possible duplicate of [Extract digits from string - StringUtils Java](https://stackoverflow.com/questions/14974033/extract-digits-from-string-stringutils-java) – Szymon Stepniak Oct 08 '17 at 06:36

4 Answers4

4

You can use the String.replaceAll method with a regular expression like this:

input.replaceAll("-?[^\\d]", "");

Adding a . will allow decimal:

input.replaceAll("-?[^\\d.]", "");

Edited to support negative numbers.

tune5ths
  • 676
  • 6
  • 18
0

use a regular expression :

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyClass {
    public static void main(String args[]) {
        String str = "asdjnk -#+-+1m245.g34.34";
        System.out.println("Input : " + str);
        double result = Double.parseDouble(extractNumber(str));
        System.out.println("Final result: " + result);    
    }

    public static String extractNumber(String input){

        //replace all characters except digits, +-.
        String regex = "[^-+0-9.]";
        input = input.replaceAll(regex, "");
        System.out.println("After remove non-digit characters: " + input);
        /* 
          number format: 
          [-]? : if there is 0 or 1 minus sign
          [0-9]+ : one or more digits
          [.]{1}[0-9]+ : . followed by one or more digits
        */
        regex = "[-]?[0-9]+([.]{1}[0-9]+)?";
        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(input);
        if(matcher.find())
            return (matcher.group(0));
        else 
            return "error, no numbers exists!";

    }

}

result:

Input : asdjnk -#+-+1m245.g34.34
After remove non-digit characters: -+-+1245.34.34
Final result: 1245.34
Ehsan
  • 311
  • 4
  • 7
  • I tried to implement this in to my code and this line_(final Matcher matcher = pattern.matcher(str);)_ came up with an error saying _change type of 'str' to 'CharSequence'_ Here is a link to my current code: bit.ly/2y78VJi – s_ofia Oct 10 '17 at 08:25
  • in your code you wrote: int str = sum; and then final Matcher matcher = pattern.matcher(str); matcher does not accept an int argument – Ehsan Oct 11 '17 at 18:06
  • Yes I do realize that it doesn't accept the int statement and with my current code(bit.ly/2y78VJi)it can only accept a _CharSequence_ which breaks everything else. – s_ofia Oct 11 '17 at 20:11
  • you should apply regex to your input, not to the sum. even before using Integer.parseint . check the edited answer. you can use the function 'extractNumber' to extract the number out of a string. and also in a calculator, use double instead of int. – Ehsan Oct 12 '17 at 16:31
0

This handles null inputs (you need to include the Apache Commons Lang library, version 3.8 or higher, in your project):

import org.apache.commons.lang3.RegExUtils;
input = RegExUtils.removeAll(input, "-?[^\\d.]");

Library reference: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RegExUtils.html

Yury
  • 722
  • 7
  • 14
-1

You can use this method to convert your string to only numericals:

 public String getNumericString(String ourString)
  {

    StringBuilder neededCharacters = new StringBuilder();

    //Read throught the entire length of your input string
    for(int i = 0;i<ourString.length();i++)
    {
      //Get the current character
        char ch = ourString.charAt(i);

   //Check if the character is a numerical
        if (Character.isDigit(ch))
        {
         //if the character is a number then add it to our string 
        // builder
            neededCharacters.append(r.charAt(i));

        }
    }
    onlyNumericalString = needed.toString();
    return onlyNumericalString;
   }

You can ask me if you don't understand anything in the code.You should make small edits depending on your needs.

Arjun Anil
  • 97
  • 12