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);

    }
}
4
  • 1
    input1 = input1.replaceAll("\D", ""); Commented Oct 8, 2017 at 6:23
  • A possible duplicate of this issue - stackoverflow.com/questions/14974033/… Commented Oct 8, 2017 at 6: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? Commented Oct 8, 2017 at 6:24
  • Possible duplicate of Extract digits from string - StringUtils Java Commented Oct 8, 2017 at 6:36

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What about negative number?
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

4 Comments

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
in your code you wrote: int str = sum; and then final Matcher matcher = pattern.matcher(str); matcher does not accept an int argument
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.
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.
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

Comments

-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.

2 Comments

I only made a few edits to the code but it works great now!
This is a terribly inefficient way of doing this. Why not use regex? It's so much faster and so much less code.

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.