Roger
Roger

Reputation: 597

Switch statement inside a while loop

I have a function which is supposed to act like a cash register. It is suppose to deduct money as long as the change is bigger than 0. However, I don't think the loop or switch statement is working properly as the values are not being deducted and returned to my variable or array. When I view my array the value should be deducted.

The code:

function checkCashRegister(price, cash, cid) {
  var change = cash - price;
  var message = "";
  var isBoolean = true;
  var cashInReg = cid;

  while(isBoolean) {
    switch (change) {
        case change -100 > 0:
          change-= 100;
          cashInReg[8][1]-= 100;
          break;
        case change -20 > 0:
          break;
        case change -10 > 0:
          break;
        case change -5 > 0:
          break;
        case change -1 > 0:
          break;
        case change -0.25 > 0:
          break;
        case change -0.10 > 0:
          break;
        case change -0.05 > 0:
          break;
        case change -0.01 > 0:
          break;
        case change === 0:
          isBoolean = false;
          break;
        case change < 0:
          message = "Insufficient Funds";
          isBoolean = false;
          break;
      default:
          message = "hi";
    }
  }

  return cashInReg;
}



checkCashRegister(100,500.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);

Upvotes: 0

Views: 5451

Answers (1)

kourouma_coder
kourouma_coder

Reputation: 1098

From MDN website

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.

In your code, normally changeshould be compare to the value in case construct which happen to be in (your code a boolean). case change -100 > 0:

I recommend that you use if else if else if ... else construct.


Good luck.

Upvotes: 2

Related Questions