Java 如果字符串结尾和指定字符之间未出现小数,则向字符串添加小数
我正在写一个基本的计算器程序,正在实现小数。在试图设计一种将十进制数附加到操作数的方法时,我遇到了十进制重复的问题Java 如果字符串结尾和指定字符之间未出现小数,则向字符串添加小数,java,regex,string,Java,Regex,String,我正在写一个基本的计算器程序,正在实现小数。在试图设计一种将十进制数附加到操作数的方法时,我遇到了十进制重复的问题 "5.5.5" // shouldn't be possible, ignore second . addition "5.5 + 5.5" or "5 + 5.5" // wonderful! 我有一些这样的代码: String expression = ""; ... //various methods to append numbers, operators, etc to
"5.5.5" // shouldn't be possible, ignore second . addition
"5.5 + 5.5" or "5 + 5.5" // wonderful!
我有一些这样的代码:
String expression = "";
...
//various methods to append numbers, operators, etc to string
...
addDecimal() {
if (expression.equals("")) {
expression += "0."; // if no operand, assume it's 0-point-something
} else {
if(/* some condition */) {
expression += ".";
//note it is appending a decimal to the end of the expression
//ie at the end of the rightmost operand
}
}
}
运算符是+
,-
,*
,/
。对于我尝试做的事情,更具声明性的描述是:
check string if it contains a decimal
if not, addDecimal()
if so, split string by operators above, look at the rightmost operand; does it contain a decimal?
if not, addDecimal()
if so, do nothing
例如
同余规则是,小数仅附加到最右边的操作数,而不是表达式中的所有操作数。您可以使用此基于查找的正则表达式进行替换:
str = str.replaceAll("(?<!\\.)\\b\\d+\\b(?!\\.)(?!.*\\d)", "$0.");
str=str.replaceAll((?您可以使用String.split
)
例如
String[] splitExpression = expression.split(".");
if(splitExpression.length > 2){
expression = splitExpression[0] + "." + splitExpression[1];
}
else {
// Either a valid decimal or no decimal number at all
}
你的方法看起来是有争议的。我会修改你在你的体系结构中使用的实体。例如,我不倾向于考虑“5.5 + 4”的表达式。我首先要建立一个不尊重“表达式”的数字,然后把它插入到“表达式”@ AlxyR..因为它是一个计算器,它是按步骤(按键)来完成的。可以假设一个人在小数之后会输入另一个数字,或者我会考虑一个“4”,意思是“4”,就像我和“…”变成“0”一样。“。我明白了。很抱歉,不太清楚输入应该是什么。那么实现一种状态机可能是有意义的,这种状态机由一个符号提供,并根据它当前的状态做出决定。“2+5”呢?这会产生“2.5”。“2+5”预计是“2+5”。如果预期5.5+4
将变为5.5+4.
(两个小数),那么为什么2+5
不应变为2.+5.
?可能只需要在5后面追加一个小数,而不是在2后面追加一个小数?并非每个操作数都需要一个小数。
String[] splitExpression = expression.split(".");
if(splitExpression.length > 2){
expression = splitExpression[0] + "." + splitExpression[1];
}
else {
// Either a valid decimal or no decimal number at all
}