I am trying to perform calculator operation, depending on the input values and the operator the result should be displayed. I am struck with validation of dividing by 0 and I am not able to display the result in another function. Please someone could help me!
function calCaulation(e) {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("oper").value;
var a = "";
if ((isNaN(x) || x == "") || (isNaN(y) || y == "")) {
a = "Sum:Please enter the valid Number";
}
if (z == "/" && y == 0) {
a = "Divide By Zero Error";
}
return a;
}
else {
var x = parseFloat(document.getElementById("first").value);
var y = parseFloat(document.getElementById("second").value);
switch (z) {
case ("+"):
a = "Sum:" + ((x + y).toFixed(2));
break;
case ("-"):
a = "Sub:" + ((x - y).toFixed(2));
break;
case ("*"):
a = "Mul:" + ((x * y).toFixed(2));
break;
case ("/"):
a = "Div:" + ((x / y).toFixed(2));
break;
default:
a = "Invalid Operator";
}
return a;
}
}
You have a bracket and else clause too much.
See here for a working jsfiddle.
https://jsfiddle.net/r2aq88tu/4/
edit: also, your return statement after the error checks would leave the function before the real code would execute, I moved the return a inside each if to make it work.
Your new code:
function calCaulation(e) {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("oper").value;
var a = "";
if ((isNaN(x) || x == "") || (isNaN(y) || y == "")) {
a = "Sum:Please enter the valid Number";
return a;
}
if (z == "/" && y == 0) {
a = "Divide By Zero Error";
return a;
}
var x = parseFloat(x);
var y = parseFloat(y);
switch (z) {
case ("+"):
a = "Sum:" + ((x + y).toFixed(2));
break;
case ("-"):
a = "Sub:" + ((x - y).toFixed(2));
break;
case ("*"):
a = "Mul:" + ((x * y).toFixed(2));
break;
case ("/"):
a = "Div:" + ((x / y).toFixed(2));
break;
default:
a = "Invalid Operator";
}
return a;
}
Related
My task was to try and code the game of Pig. I am trying to have the code use a switch statement to determine which chunk of code to follow but it is skipping case 1 and case 2 and going directly to the default case. The roll.score is coming from this Javascript file:
function Dice(d1, d2){ //d1 = die 1 d2 = die 2
this.d1 = d1?d1:parseInt(Math.random()*6 + 1);
this.d2 = d2?d2:parseInt(Math.random()*6 + 1);
}
Dice.prototype.score = function(){ //d1 = die 1 d2 = die 2
if(this.d1 == 1 || this.d2 == 1){
return 1; //return score 0 for turn
}else if(this.d1 == 1 && this.d2 == 1){
return 2; //return 13 as code to reset score to 0
}else
return parseInt(this.d1 + this.d2);
}
Dice.prototype.toString = function(){
return "Rolled " + this.d1 + " and " + this.d2;
}
What it is supposed to do is return either 1, 2, or whatever the 2 number added together are. Like I mentioned above, no matter what the roll.score() returns, the switch statement always goes to the default case.
var again = true;
do {
var roll = new Dice(parseInt(Math.random() * 6 + 1), parseInt(Math.random() * 6 + 1));
window.alert(roll.toString());
turnCounter++;
switch (roll.score) {
case 1: // 1 die = 1
playerScore = roll.score();
again = false;
rollCounter++;
turnCounter++;
document.write("Enters case 1");
break;
case 2: //2 = snake eyes
playerTotal = 0;
playerScore = 0;
again = false;
rollCounter++;
turnCounter++;
break;
default:
playerScore += roll.score();
rollCounter++;
displayScore();
document.write(roll.score() + "<br/>");
var rollAgain = window.prompt("Do you want to roll again?(Y/N)");
if (rollAgain.toUpperCase() === "N") {
again = false;
playerTotal += playerScore;
displayScore();
turnCounter++;
if (playerScore > highScore)
highScore = playerScore;
}
break;
}
rollCounter++;
}while (again);
switch (roll.score) { is not the same as switch (roll.score()) {
roll.score is a function, whereas you want to switch on the result on the returned result (roll.score()).
So I try build my own Javascript calculator as an exercise. Unfortunately when I try to use the eval() function with "=" button click to convert string into result, for example "2+2*2", nothing happens. Here's my code:
var draw = document.getElementById("result");
function calc(x) {
draw.innerHTML += x;
if (x === '=') {
draw.innerHTML = eval(draw.innerHTML);
} else if (x === 'c') {
draw.innerHTML = '0';
} else if (x === 'sqrt') {
draw.innerHTML = Math.sqrt(eval(draw.innerHTML));
} else if (x === 'pow') {
draw.innerHTML = Math.pow(eval(draw.innerHTML));
}
}
draw.innerHTML += x;
means if e.g. your string is 2*2 and you call
calc("sqrt")
the draws content will be
"2*2sqrt"
and thats not a valid expression, therefore the eval will fail. You may want to only concat if its not an operation:
function calc(x) {
if (x === '=') {
return draw.innerHTML = eval(draw.innerHTML);
} else if (x === 'c') {
return draw.innerHTML = '0';
} else if (x === 'sqrt') {
return draw.innerHTML = Math.sqrt(eval(draw.innerHTML));
} else if (x === 'pow') {
return draw.innerHTML = Math.pow(eval(draw.innerHTML),2);
}
draw.innerHTML += x;
}
That can be beautified with an object as a lookup table:
const result = n => eval(n),
sqrt = n => Math.sqrt(eval(n)),
pow = n => Math.pow(eval(n),2),
default = (n, add) => n + add;
function calc(in){
draw.innerHTML = ({"=":result, sqrt, pow}[in] || default)(draw.innerHTML, in);
}
Some time ago I wrote this fun grid that is offset to look like a hexagonal grid. I added a feature to check if any two points are touching. I thought it was brilliant until I finally found a bug and am not sure how to correct it.
If you press (1,4) and (2,5) you will see that they are "touching" but they shouldn't be. What logic am I missing in the function isTouchingHex?
Found bugs so far..
(1,4) & (2,5)
(2,2) & (3,3)
(0,0) & (1,1)
CodePen
var $point1 = $('#point1');
var $point2 = $('#point2');
var $dx = $('#dx');
var $dy = $('#dy');
var $isTouching = $('#isTouching');
var $table = $('#hexTable');
var table = [];
var rows = 10;
var cols = 5;
var point1 = null;
var point2 = null;
var clickedCount = 0;
for (let y = 0; y < rows; y++) {
var $tr = $('<div class="hexagonRow"></div>')
var row = [];
for (let x = 0; x < cols; x++) {
var $col = $('<div class="hexagon"><div class="hexagonText">' + x + ',' + y + '</div></div>');
$col.click(function() {
if (clickPoint(x, y))
$(this).toggleClass('clicked');
});
$tr.append($col);
row.push(y);
}
$table.append($tr);
table.push(row);
}
function clickPoint(x, y) {
var clicked = true;
if (point1 && point1[0] === x && point1[1] === y) {
point1 = null;
clickedCount--;
} else if (point2 && point2[0] === x && point2[1] === y) {
point2 = null;
clickedCount--;
} else if (!point1 && clickedCount < 3) {
point1 = [x, y];
clickedCount++;
} else if (!point2 && clickedCount < 3) {
point2 = [x, y];
clickedCount++;
} else {
clicked = false;
}
updateDisplay();
return clicked;
}
function updateDisplay() {
if (point1)
$point1.html(point1[0] + ',' + point1[1])
else
$point1.html('');
if (point2)
$point2.html(point2[0] + ',' + point2[1])
else
$point2.html('');
if (point1 && point2) {
var touching = isTouchingHex(point1[0], point1[1], point2[0], point2[1]) ? 'true' : 'false';
$isTouching.html(touching)
} else {
$isTouching.html('');
}
}
function isTouchingHex(x1, y1, x2, y2) {
var deltaX = x1 - x2;
var deltaY = y1 - y2;
$dx.html(deltaX);
$dy.html(deltaY);
// check same x
if (deltaX === 0) {
switch (deltaY) {
// check bottom left
case -1:
// check bottom
case -2:
// check top right
case 1:
// check above
case 2:
return true;
break;
}
} else if (deltaX === 1) {
switch (deltaY) {
// check bottom left
case -1:
// check top left
case 1:
return true;
break;
}
}else if (deltaX === -1) {
switch (deltaY) {
// check bottom right
case -1:
return true;
break;
}
}
return false;
}
When I attempt to move the div (tank) to the right ONLY in the first "movement command", and only in that direction, I come across in issue whereby my div shoots off a few thousand pixels to the right, way off of the screen region. Was hoping someone would assist me to see why this is.
function animate() {
var tank = document.getElementById("tank");
tank.style.marginLeft="360px";
tank.style.marginTop="440px";
window.xpos = tank.style.marginLeft;
window.ypos = tank.style.marginTop;
window.x = xpos.replace("px","");
window.y = ypos.replace("px","");
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '37') {
if (x > 0) {
x = x - 20;
tank.style.marginLeft = x + "px";
}
} else if (e.keyCode == '39') {
if (x < 70) {
x = x + 20;
tank.style.marginLeft = x + "px";
}
} else if (e.keyCode == '38') {
if (y > 0) {
y = y - 20;
tank.style.marginTop = y + "px";
}
} else if (e.keyCode == '40') {
if (y < 440) {
y = y + 20;
tank.style.marginTop = y + "px";
}
}
}
checkKey(e);
}
window.lives = 3;
function destroy() {
if (lives != 0) {
alert("Life Lost!");
lives--;
window.collision == false;
animate();
} else {
alert("Try Again!");
}
}
window.collision = true;
function state() {
if (collision == false) {
window.state = 1;
} else if (collision == true) {
window.state = 0;
}
return state;
}
state();
if (state == 1) {
animate();
} else {
destroy();
}
You think you are doing a math operation but what you really are doing a string concatenation. In Javascript "360"-20 equals 340 because in this case the string is converted to a number and then an arithmetic subtraction is performed with both numeric values, however a different set of rules apply for the plus operator: in this case "360"+20 yields "36020" because the number is converted to a string and then both strings are concatenated.
Do this:
window.x = Number(xpos.replace("px",""));
window.y = Number(ypos.replace("px",""));
I have a form that I'm using to calculate some numbers, and the final 3 input fields on the form are disabled because they show the results of the calculator.
I'm using the following javascript/jquery to add commas to the user editable fields which works great but I can't seem to find a way to add commas to the "results" fields:
$('input.seperator').change(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
This is what I'm using the populate the fields, basically the fields show the results in dollars, so I'm trying to add a comma every 3 numbers:
$('#incorrect-payment').val(fieldK);
$('#correcting-payment').val(fieldL);
$('#total-cost').val(fieldM);
I think you'd want to use a function like this:
function FormatCurrency(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var i = parseFloat(amount);
if (isNaN(i)) { i = 0.00; }
var minus = false;
if (i < 0) { minus = true; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (showDecimals) {
if (s.indexOf('.') < 0) { s += '.00'; }
if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
}
//s = minus + s;
s = '$' + FormatCommas(s, showDecimals);
if (minus)
s = "(" + s + ")";
return s;
}
function FormatCommas(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) { return ''; }
var minus = '';
if (i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if (!showDecimals) {
amount = n;
}
else {
if (d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
}
amount = minus + amount;
return amount;
}
May be you might want to trigger change event manually through javascript for your three read-only input fields. Using jquery trigger . I am not sure but it seems like a bad idea to have a read-only input field if no user can change these values. Usually having read-only input fields is good if a user with some security can edit those and some cannot.