简体   繁体   中英

How to prevent Zero from appearing in Calculator?

I am writing a FreeCodeCamp Calculator. The problem that I am working on right now is repeating operators. For example, if I press "5" and then "+", but changed my mind and pressed "-", the history area should display "5-" instead of "5+". However, with my code, it display "5+0-". Therefore, I realize that I will need to fix the "Zero" problem as well.

The list I wanted to do for the "Zero" problem are:

  1. If one press "0", allow it to appear in the history area. For example, if someone press "0" and then the operator, it should appear in the history area as "0-".
  2. Otherwise, if someone press operator first without putting in any number, stop this method

Here is my code from this 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>

All the action is happening in function addOperator(keyitem) . I have attempt to fix the "Zero" problem, but I commented it out so you can see fully what I am talking about. Here is the code that I commented out.

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

I look forward to any suggestions or code solutions that can help me fix the "Zero" problem.

I would reconsider the inital value from "0" to null to be able to split zero-logic and init-logic:

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);

It's just an idea, and the approach should be improved, but the interim result you may try on your codepen fork .

In your "addOperator" function you'll just need a simple if statement, check whether or not the last character in your string is an operator. If it is then swap it, if it isn't than add the given operator

EDIT:

I looked through the code some more and looks like it's a little more complex than a single if statement and would require quite a bit of rewriting. All I can really offer is a different way of going about storing your values.

I would recommend storing an array of the actual button presses as soon as the button is pressed, and then modify that list within your individual button functions, then from that list generate you're display. For example, if the user were to press 1, +, 2, 3, -, +, = the array would look like this:

[] -> []

[1] -> [1]

[1,+] -> [1,+]

[1,+,2] -> [1,+,2]

[1,+,2,3] -> [1,+,23] // Checked by addNumber, concats numbers

[1,+,23,-] -> [1,+,23,-]

[1,+,23,-,+] -> [1,+,23,+] // Checked by addOperator, swaps operator

[1,+,23,-,+,=] -> [] // Checked by solveEqual, solves then empties array

Having this as a global variable would allow your button functions to modify the array as opposed to pushing elements from the functions as it currently is, the benefit being you wouldn't be pushing elements that shouldn't be pushed like nulls or operators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM