私は基本的な電卓プログラムを作成しています。オペランドに小数点を追加する方法を考案する際に、私は小数点の重複の問題に遭遇します。文字列の末尾と指定された文字の間に10進数が表示されない場合は、文字列に小数点を追加してください。
"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
など。
expression = "2";
addDecimal(); //expression is now "2."
//append decimal to only operand
expression = "5.5 + 4";
addDecimal(); //expression is now "5.5 + 4."
//append a decimal to rightmost operand
expression = "7.5";
addDecimal(); //expression is now "7.5"
//if an operand contains a decimal already, it cannot have another
expression = "2 + 5";
addDecimal(); //expression is now "2 + 5."
//note the decimal was only appended to the rightmost operand
//ignoring the leftmost operand
合同ルールは小数のみない表現内のすべてのオペランドに、右端のオペランドに付加されることです。
あなたのアプローチは疑わしいですね。あなたのアーキテクチャで使用しているエンティティを改訂します。例えば、私は「5.5 + 4」とは考えていません。表現。私は最初に「表現」とは関係のない数字を作成し、それを「表現」 –
@ AlexeyR.に挿入します。それは電卓です。これはステップ(キー押し)で行われます。人が10進数の後に別の数字を入力すると仮定するか、または「4」と考えるでしょう。私が "やった"のように "4.0"を意味する「0」になる。 – gator
私は参照してください。申し訳ありませんが、入力が何であるかははっきりしていませんでした。それから、シンボルが与えられ、現在の状態に応じて決定を下すような種類の状態マシンを実装するのが理にかなっています。 –