如何防止Zero出现在计算器中?

时间:2017-11-15 17:34:43

标签: javascript jquery calculator

我正在写一个FreeCodeCamp计算器。我现在正在处理的问题是重复运算符。例如,如果我按" 5"然后" +",但改变了我的想法并按下了#34; - ",历史区域应该显示" 5 - "而不是" 5 +"。但是,使用我的代码,它会显示" 5 + 0 - "。因此,我意识到我需要修复" Zero"问题也是如此。

我想为" Zero"做的清单问题是:

  1. 如果按一下" 0",则允许它出现在历史记录区域中。例如,如果有人按下" 0"然后是操作员,它应该在历史区域中显示为" 0 - "。
  2. 否则,如果有人先按操作员而不输入任何号码,请停止此方法
  3. 以下是我Codepen的代码:

    
    
    $(document).ready(function() {
      
      var mainMath = "0";
      var subMath = "0";
      var finalset = "";
      var subMatharray = [];
      var oppArray = [];
      var equalPressed = false;
      var prevKey = "";
      update();
      
      $("button").click(function(){
        calculate($(this).attr("value"));
      });
      
      function calculate(keyitem) {
        console.log("buttonpress: " + keyitem);
        switch(keyitem) {
          case "clear":
            clearScreen();
            break;
          case "%":
            percentageScreen();
            break;
          case "/":
          case "*":
          case "+":
          case "-":
            addOperator(keyitem);
            break;
          case "plusminus":
            plusminusScreen();
            break;
          case "0":
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            addNumber(keyitem);
            break;
          case ".":
            addDecimal(keyitem);
            break;
          case "=":
            solveEqual(keyitem);
            break;
        }
        update();
        };
     
      function clearScreen() {
         mainMath = "0";
         subMath = "0";
         prevKey = "";
         subMatharray = [];
         oppArray = [];
        if(mainMath.length > 0){
          $(".entry").css("font-size", "4em");
        }
        console.log("clearMain: " + mainMath);
        console.log("clearSub: " + subMath);
      };
      
      function plusminusScreen() {
         mainMath = -1 * mainMath;
        finalset = mainMath;
        console.log("plusminusMain: " + mainMath);
        console.log("plusminusFinal: " + finalset);
      };
      
      function addNumber(keyitem) {
        if (mainMath == "0"){
          mainMath = keyitem/*mainMath.replace("0", keyitem);*/
          finalset = mainMath;
          return;
          console.log("addedMainZero: " + mainMath);
          console.log("addedFinalZero: " + finalset);
        }
        if (equalPressed == true){
          mainMath = keyitem;
          subMath = "0";
          subMatharray = [];
          equalPressed = false;
          console.log("addNumberEqualmain: " + mainMath);
        }
        mainMath+=keyitem;
        finalset = mainMath;
        
        console.log("addedMain: " + mainMath);
        console.log("addedFinalset: " + finalset);
        console.log("addedarray: " + subMatharray);
        
        if(mainMath.length > 8){
          $(".entry").css("font-size", "1.5em");
        }
        
      };
      
      function addOperator(keyitem){
        
        if (equalPressed == true){
          subMatharray = [];
          equalPressed = false;
          console.log("addOpEqualarray: " + subMatharray);
        }
        /*if (mainMath == "0" && finalset !== "0"){
          mainMath = "0";
          subMatharray.push(keyitem);
          return;
          console.log("addedMainZero: " + mainMath);
          console.log("addedFinalZero: " + finalset);
        }*/
        
        oppArray.push(keyitem);
        console.log("addOpArray: " + oppArray);
        var opkeyitem = "";
        
        subMatharray.push(mainMath);
        prevKey = "numbertest";
        
        if(prevKey == "numbertest") {
          subMatharray.push(keyitem);
          prevKey = "operatortest";
          console.log("addOpArraySubArrayElse: " + subMatharray);
          console.log("addOpArrayPrevKeyElse: " + prevKey);
        } /*else if (oppArray.length > 1 && prevKey == "operatortest") {
          subMatharray.pop();
          subMatharray.push("droubletest");
          oppArray = [];
          console.log("addOpArraySubArray: " + subMatharray);
          console.log("addOpArrayPrevKey: " + prevKey);
        } /*else if(prevKey == "numbertest") {
          subMatharray.push(keyitem);
          prevKey = "operatortest";
          console.log("addOpArraySubArrayElse: " + subMatharray);
          console.log("addOpArrayPrevKeyElse: " + prevKey);
        }*/
        
        subMath = subMatharray.join("");
        mainMath = "0";
        prevKey = keyitem;
        console.log("addOpSub: " + subMath);
        console.log("addOpMain: " + mainMath);
        console.log("addOpMainarray: " + subMatharray);
        console.log("equaltrueTest: " + equalPressed);
      };
      
      function addDecimal(keyitem){
        if (mainMath.indexOf(keyitem) === -1){
          if(mainMath == "0") {
            mainMath = "0" + keyitem;
            return;
          }
        } else {
            return;
          }
        addNumber(keyitem);
      };
      
      function solveEqual(keyitem) {
        subMatharray.push(finalset);
        subMath = subMatharray.join("");
        mainMath = eval(subMath);
        console.log("solveEqualresult: " + mainMath);
        console.log("solveEqualhistory: " + subMath);
        console.log("solveEqualarray: " + subMatharray);
        var finalresult = mainMath.toString();
        if(finalresult.length > 8){
          $(".entry").css("font-size", "1.5em");
        }
        equalPressed = true;
      };
      
      function update(){
      $("#answer").html(mainMath);
      $("#history").html(subMath);
    };
      
    });
    
    /*Problems
    2. I need to work on percentage button soon...
    3. fix the problem if someone click an operator more than one.
    */
    
    @import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
    h1, h2, h3, p {
      font-family: 'Roboto', sans-serif;
    }
    html, body{
      height:100%;
      margin: 0;
      background-color: #ffffff;
    }
    .wrapper {
      width: 100%;
      height: 100%;
      position: relative;
      display:flex;
      flex-direction:column;
      justify-content:center;
      align-items:center;
      background-repeat: no-repeat;
        background-size: cover;
      background-position: center center;
      padding: 160px 0;
    }
    .calculatorbox {
      width: 300px;
      margin: 0 auto;
      border: 1px solid #000000;
    }
    .calheader {
      text-align: center;
    }
    .calwindow {
      background: #000000;
      position: relative;
      display: -webkit-box;
      display: -moz-box;
      display: -ms-flexbox;
      display: -webkit-flex;
      display: flex;
       -webkit-flex-direction: column; /* Safari */
      flex-direction:         column;
      -webkit-justify-content: flex-end;
      justify-content: flex-end;
      -webkit-align-items: flex-end;
      align-items: flex-end;
      padding: 10px 0;
      box-sizing: border-box;
    }
    .entry {
      font-size: 4em;
      display: block;
      line-height: 1em;
    }
    .entryhistory {
      font-size: 1em;
      letter-spacing: 2px;
      padding-right: 5px;
    }
    .entry p, .entryhistory p {
      margin: 0;
      color: #ffffff;
    }
    sup {
      top: -0.5em;
    }
     
    sub {
      bottom: -0em;
    }
    .row {
      clear: both;
      width: 100%;
      display: flex;
    }
    button {
      display: inline-block;
      border: none;
      padding: 0;
      outline: none;
      cursor: pointer;
    }
    .key {
      width: 75px;
      height: 70px;
      font-size: 22px;
      border-top: 1px solid rgba(0, 0, 0, 0.3);
      border-right: 1px solid rgba(0, 0, 0, 0.3);
      box-sizing: border-box;
    }
    .key.btnspan {
      width: 150px;
    }
    .key.topcolor {
      background: #d9d9d9;
    }
    .key.orange {
      background: #ff8c00;
      color: #ffffff;
    }
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="wrapper">
      <div class="calheader">
          <h2>Simple Calculator</h2>
        </div>
      <div class="calculatorbox">
        <div class="calwindow">
          <!-- ENTRY BOX -->
          <div class="entry">
            <p id="answer"></p>
          </div>
          <div class="entryhistory">
            <p id="history"></p>
          </div>
        </div>
        <!-- BUTTONS -->
        <div class="calbuttons">
          <div class="row">
            <button class="key topcolor" value="clear">C</button>
            <button class="key topcolor" value="plusminus"><sup>+</sup>/<sub>−</sub></button>
            <button class="key topcolor" value="%">%</button>
            <button class="key orange" value="/">÷</button>
          </div>
          <div class="row">
            <button class="key" value="7">7</button>
            <button class="key" value="8">8</button>
            <button class="key" value="9">9</button>
            <button class="key orange" value="*">×</button>
          </div>
          <div class="row">
            <button class="key" value="4">4</button>
            <button class="key" value="5">5</button>
            <button class="key" value="6">6</button>
            <button class="key orange" value="-">−</button>
          </div>
          <div class="row">
            <button class="key" value="1">1</button>
            <button class="key" value="2">2</button>
            <button class="key" value="3">3</button>
            <button class="key orange" value="+">+</button>
          </div>
          <div class="row">
            <button class="key btnspan" value="0">0</button>
            <button class="key" value=".">.</button>
            <button class="key orange" value="=">=</button>
          </div>
        </div>
      </div>
    </div>
    &#13;
    &#13;
    &#13;

    所有行动都发生在function addOperator(keyitem)。我试图修复&#34; Zero&#34;问题,但我评论了它,所以你可以完全看到我在说什么。这是我评论过的代码。

    if (mainMath == "0" && finalset !== "0"){
          mainMath = "0";
          subMatharray.push(keyitem);
          return;
          console.log("addedMainZero: " + mainMath);
          console.log("addedFinalZero: " + finalset);
        }
    

    我期待任何可以帮助我修复&#34; Zero&#34;问题。

2 个答案:

答案 0 :(得分:1)

我会重新考虑从“0”到初始值的初始值,以便能够拆分零逻辑和初始逻辑:

var mainMath = null;
// ...

function clearScreen() {
  mainMath = null;
  // ...
}

function addNumber(keyitem) {
  if (mainMath === null) { 
    mainMath = "0"; //hacky, I know, this requires more deep refactoring
  }
  // ...
}

function addOperator(keyitem){
  if(mainMath === null) {
    return; // this is the main point
  }
  // ...    
  mainMath = null;
  // ...
}

$("#answer").html(mainMath === null ? "0" : mainMath);

这只是一个想法,应该改进方法,但是你可以试试codepen fork的中期结果。

答案 1 :(得分:1)

在“addOperator”函数中,您只需要一个简单的if语句,检查字符串中的最后一个字符是否为运算符。如果它是交换它,如果它不是添加给定的运算符

编辑:

我仔细查看了代码,看起来它比单个if语句稍微复杂一点,并且需要相当多的重写。我真正能提供的只是存储价值观的另一种方式。

我建议按下按钮后立即存储按下实际按钮的数组,然后在各个按钮功能中修改该列表,然后从该列表生成您的显示。例如,如果用户按1,+,2,3, - ,+,=数组将如下所示:

[] - &gt; []

[1] - &gt; [1]

[1,+] - &gt; [1,+]

[1,+,2] - &gt; [1,+,2]

[1,+,2,3] - &gt; [1,+,23] //由addNumber检查,concats数字

[1,+,23, - ] - &gt; [1,+,23, - ]

[1,+,23, - ,+] - &gt; [1,+,23,+] //由addOperator检查,交换运算符

[1,+,23, - ,+,=] - &gt; [] //由solveEqual检查,解决然后清空数组

将此作为全局变量将允许您的按钮功能修改数组,而不是从当前的函数中推送元素,这样做的好处是你不会不要推动不应该像空值或运算符一样推送的元素