我正在尝试创建一个基本的计算器程序,我想从字符串输入中删除所有 非数字字符 。 (我是一个java 新手 )。这是我的 当前代码:
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);
}
}
答案 0 :(得分:3)
您可以将String.replaceAll方法与正则表达式一起使用,如下所示:
input.replaceAll("-?[^\\d]", "");
添加。将允许十进制:
input.replaceAll("-?[^\\d.]", "");
编辑支持负数。
答案 1 :(得分:0)
使用正则表达式:
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!";
}
}
结果:
Input : asdjnk -#+-+1m245.g34.34
After remove non-digit characters: -+-+1245.34.34
Final result: 1245.34
答案 2 :(得分:0)
这处理空输入(您需要在项目中包括3.8或更高版本的Apache Commons Lang库):
import org.apache.commons.lang3.RegExUtils;
input = RegExUtils.removeAll(input, "-?[^\\d.]");
图书馆参考:https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RegExUtils.html
答案 3 :(得分:-1)
您可以使用此方法将字符串转换为仅数字:
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;
}
您可以问我是否对代码中的任何内容一无所知。您应该根据自己的需要进行少量修改。