2017-10-16 3 views
1

私は基本的な電卓プログラムを作成しています。オペランドに小数点を追加する方法を考案する際に、私は小数点の重複の問題に遭遇します。文字列の末尾と指定された文字の間に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 

合同ルールは小数のみない表現内のすべてのオペランドに、右端のオペランドに付加されることです。

+0

あなたのアプローチは疑わしいですね。あなたのアーキテクチャで使用しているエンティティを改訂します。例えば、私は「5.5 + 4」とは考えていません。表現。私は最初に「表現」とは関係のない数字を作成し、それを「表現」 –

+0

@ AlexeyR.に挿入します。それは電卓です。これはステップ(キー押し)で行われます。人が10進数の後に別の数字を入力すると仮定するか、または「4」と考えるでしょう。私が "やった"のように "4.0"を意味する「0」になる。 – gator

+0

私は参照してください。申し訳ありませんが、入力が何であるかははっきりしていませんでした。それから、シンボルが与えられ、現在の状態に応じて決定を下すような種類の状態マシンを実装するのが理にかなっています。 –

答えて

0

あなたは、交換のために、この前後参照ベースの正規表現を使用することができます

str = str.replaceAll("(?<!\\.)\\b\\d+\\b(?!\\.)(?!.*\\d)", "$0."); 

RegEx Demo

正規表現の分裂:

  • (?<!\\.):私たちは前の位置にドットを持っていないアサートを
  • \\b\\d+\\b:1つにマッチするまたはワード境界
  • (?!\\.)でより多くの桁:我々は先に
  • (?!.*\d)ドットを持っていないアサート:あなたはString.splitを使用することができ
+0

「2 + 5」はどうですか?これにより、「2. + 5」が得られる。期待される場合は「2 + 5」となります。 – gator

+0

'5.5 + 4'が' 5.5 + 4.'(両方の小数点以下)になることが期待される場合、 '2 + 5'は' 2. + 5.'にならないのはなぜですか? – anubhava

+0

おそらく小数点は、2ではなく5に付加されることが望ましいだけでしょうか?すべてのオペランドが小数を必要とするわけではありません。 – gator

-1

我々は右のほとんどのオペランドであることを確認します。

String[] splitExpression = expression.split("."); 
if(splitExpression.length > 2){ 
    expression = splitExpression[0] + "." + splitExpression[1]; 
} 
else { 
    // Either a valid decimal or no decimal number at all 
} 
関連する問題