Problem trying to create a calculate program - javascript

I'm trying to create a calculator program for my assignment course in JavaScript. The program has to calculate to numbers (values assigned by the user), as well as the operator (+, - , * ,/), and to display the result.
If the user input an extra character in the field like (15n + 20 or 15 ++ 20 or 15+ + 20) has to display an error "Cannot concatenate a number with a string"
if the user divide a number by 0 has to display "Division by 0 is not allowed"
Please I really need your help.
I posted, my code bellow, let me know. What I'm doing wrong?
I want to mention that I'm at the beginning level.
Thanks, I appreciate all the advices
let numberOne = parseFloat(prompt("First Number: "));
let operator = prompt("Chose operation (+ - * /): ");
let numberTwo = parseFloat(prompt("Second Number: " ));
function DivisionByZero(a, b) {
if (a == 0 || b == 0 == true) {
throw "Divizion by 0 is not allowed";
}
}
function TypingError(a, b, c) {
if (numberOne + " " == true) {
throw "Cannot concatenate a number with a string";
} else if (numberTwo + " " == true) {
throw "Cannot concatenate a number with a string";
} else if (operator + operator == true) {
throw "Can not concatenate two operators"
}
}
let TypingErrorDisplay = TypingError(numberOne, operator, numberTwo);
var ErrorDivisionDisplay = DivisionByZero(numberOne, numberTwo);
if (operator === "+") {
var calc = parseFloat(numberOne) + parseFloat(numberTwo);
alert(calc);
}
else if (operator === "-") {
var calc = parseFloat(numberOne) - parseFloat(numberTwo);
alert(calc);
}
else if (operator === "*") {
var calc = parseFloat(numberOne) * parseFloat(numberTwo);
alert(calc);
}
else if (operator === "/") {
var calc = parseFloat(numberOne) / parseFloat(numberTwo);
alert(calc);
if (ErrorDivisionDisplay == true) {
alert("Division by 0 is not allowed");
}
}
else {
alert(TypingErrorDisplay);
}

First of all,
in your first condition you have
function DivisionByZero(a, b) {
if (a == 0 || b == 0 == true) {
throw "Divizion by 0 is not allowed";
}
}
You can't have b == 0 == true.
You just need :
function DivisionByZero(a, b) {
if (a === 0 || b === 0) {
throw "Divizion by 0 is not allowed";
}
}
for the rest, you should check that post : Check if a variable is a string in JavaScript
function TypingError(a, b, c) {
if (typeOf(numberOne) == "string") {
throw "Cannot concatenate a number with a string";
}
else if (typeOf(numberTwo) === "string") {
throw "Cannot concatenate a number with a string";
}
else if (operator.lenght > 1) {
throw "Can not concatenate two operators"
}
}
Try to correct that things fisrt and tell us.
Axel,

let numberOne = parseFloat(prompt("First Number: "));
let operator = prompt("Chose operation (+ - * /): ");
let numberTwo = parseFloat(prompt("Second Number: " ));
function DivisionByZero(a, b) {
if (a == 0 || b == 0) { // You don't need == true, you already declared the conditions
throw "Divizion by 0 is not allowed";
}
}
function TypingError(n1, op, n2) {
if (!n1.isFinite()) { // Triggers if numberOne is not finite
throw "Cannot concatenate a number with a string";
} else if (!n2.isFinite()) { // Triggers if numberTwo is not finite
throw "Cannot concatenate a number with a string";
} else if (op != "+" && op != "-" && op != "*" && op != "/") { // Accept only valid arithmetic operators
throw "Can not concatenate two operators"
}
}
let TypingErrorDisplay = TypingError(numberOne, operator, numberTwo);
var ErrorDivisionDisplay = DivisionByZero(numberOne, numberTwo);
if (operator === "+") {
var calc = parseFloat(numberOne) + parseFloat(numberTwo);
alert(calc);
}
else if (operator === "-") {
var calc = parseFloat(numberOne) - parseFloat(numberTwo);
alert(calc);
}
else if (operator === "*") {
var calc = parseFloat(numberOne) * parseFloat(numberTwo);
alert(calc);
}
else if (operator === "/") {
var calc = parseFloat(numberOne) / parseFloat(numberTwo);
alert(calc);
if (ErrorDivisionDisplay == true) {
alert("Division by 0 is not allowed");
}
}
else {
alert(TypingErrorDisplay);
}

#Solution#
The solution that I found it is displayed below. Please let me know what you think about it.
let numberOne = prompt("First Number: ");
let operator = prompt("Chose operation (+ - * /): ");
let numberTwo = prompt("Second Number: ");
function TypingError(op1, op2, operation) {
if (isNaN(numberOne) || numberOne.length == 0 || isNaN(numberTwo) || numberTwo.length == 0) {
return -1;
}
if (operation !== undefined && operation.length > 1) {
return -2;
}
return 0;
}
let TypingErrorDisplay = TypingError(numberOne, numberTwo, operator);
if (TypingErrorDisplay == -1) {
alert("one of the operands is not numeric ");
}
else if (TypingErrorDisplay == -2) {
alert("wrong operation - symbol must have one character");
}
else {
numberOne = parseFloat(numberOne);
numberTwo = parseFloat(numberTwo);
if (operator == "+") {
var calc = numberOne + numberTwo;
alert(calc);
}
else if (operator == "-") {
var calc = numberOne - numberTwo;
alert(calc);
}
else if (operator == "*") {
var calc = numberOne * numberTwo;
alert(calc);
}
else if (operator === "/") {
if (numberTwo == 0) {
alert("Division by 0 is not allowed");
}
else {
var calc = numberOne / numberTwo;;
alert(calc);
}
}
else {
alert("operation " + operator + " not exists");
}
}

Related

Why isn't this javascript returning the expected code?

let myName = 'vincenzo';
if (myName !== String) {
console.log('this is not a string');
} else if (myName.length % 2 === 0){
console.log(even);
} else if (myName.length % 2 !== 0){
console.log(odd);
}
can anyone explain why this only returns "this is not a string"? shouldn't it return "even"? I am not sure where I am going wrong
You just have to clean up this code:
function determine(str) {
if (typeof(str) !== 'string') {
console.log('this is not a string');
} else if (str.length % 2 === 0) {
console.log('even');
} else {
console.log('odd');
}
}
determine('vincenzo');
const determinfun=(MyName)=>{
if (type of MyName !== String) {
console.log('this is not a string');
} else if (MyName.length % 2 === 0){
console.log('even');
} else if (MyName.length % 2 !== 0){
console.log('odd');
}
}
determinfun('vincenzo');
Please use the type of operator type of MyName !== String

simple calculator with javascript and it function calculator doesn't apply

I am new to Javascript so this is probably an easy fix but I cannot figure out. I am making a calculator using HTML, CSS and Javascript
and I pretty much only know about declaration, if/else statement, for/while loops and some basic elements of CSS and HTML.
here is my javascript code for the calculator.
var firstNum, operator, previousKey, previousNum;
const calculator = document.querySelector('.calculator');
const buttons = calculator.querySelector('.calculator__buttons');
const display = document.querySelector('.calculator__display');
function calculate(n1, operator, n2) {
let result = '';
if(operator === '+'){
result = n1 + n2;
}else if(operator === '-'){
result = n1 - n2;
}else if(operator === '*'){
result = n1 * n2;
}else if(operator === '/'){
result = n1 / n2;
}
return result;
}
buttons.addEventListener('click', function (event) {
const target = event.target;
const action = target.classList[0];
const buttonContent = target.textContent;
if (target.matches('button')) {
let firstNum = 0;
if (action === 'number') {
if (display.textContent > 0 ) {
display.textContent += buttonContent //
}
else {display.textContent = buttonContent}
//display.textContent = buttonContent
console.log('number1 ' + buttonContent + ' button1');
previousKey = 'number';
}
if (action === 'operator') {
console.log('operator1 ' + buttonContent + ' button1');
operator = buttonContent;
firstNum = display.textContent
//console.log(firstNum)
return firstNum
previousKey = 'operator';
}
if (action === 'decimal') {
// console.log('deciaml1');
previousKey = 'decimal';
}
if (action === 'clear') {
display.textContent = '0'
console.log('clear1');
previousKey = 'clear';
}
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(firstNum, operator, display.textContent)
previousKey = 'calculate';
}
}
});
although I set arithmetic operations above as function calculate(n1, operator, n2)
my caculator // here is what it looks like.
result of 5-9 comes out as -59.
I will appreciate if I could get some help.
thank you in advance.
The issue is that you are sending in strings to the calculate function. So you should explicitly convert the string textContent to integer values as such in your code:
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(parseInt(firstNum,10), operator, parseInt(display.textContent,10))
previousKey = 'calculate';
}

Letter decode Javascript

I am trying to write a function that will validate that all entries within the commas are numberic and display "?" if they are not. for example: user enters 2,3,5b,c7 the output that I am getting is BCE? instead of BC?? This is the decode function that I am trying to validate in:
function fnDecode() {
var msg = $("textin").value;
if(msg === "") {
$("textin_span").innerHTML = "* Please enter a value to decode
*";
$("textin").focus();
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(","); //split method separates by delimiter
var outstr = ""; //out string
for (var i=0; i<nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) { //if isNaN true, print ?
outstr += "?";
} else if (isNallN(nums[i])) { //THIS IS WHERE THE FN GOES
outstr += "?";
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 >26) {
outstr += "?";
}else {
outstr += String.fromCharCode(n2+64);
}
}
$("textout").value = outstr;
}
function isNallN(s) {
}
I corrected your fnDecode function.
You don't need multiple if to check for isNaN, !isNaN('5') will work as well as !isNaN(5). Check this Javascript Equality Table for more information.
Here, I adapted the function for it to work with a String given in
parameter and to return the wanted String.
function fnDecode(msg) {
var nums = msg.split(",");
var outstr = "";
for (num of nums) {
if (isNaN(num)) outstr += "?"; //isNaN works on "5" and 5
else if (+num === 0) outstr += " "; //We use +num to parse the String to an int
else if (+num < 1 || +num > 26) outstr += "?";
else outstr += String.fromCharCode(+num + 64);
}
return outstr;
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a shorter ES6 version :
function fnDecode(msg) {
return msg.split(',').map( num => isNaN(num) || (+num < 1 || +num > 26) ? '?' : +num == 0 ? ' ' : String.fromCharCode(+num + 64)).join('');
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));

concatenation occurs besides sum

i am trying to build a calculator but in that i am unable to perform sum operation besides it concatenation is occurred how i can do this sum, also how to empty the text box when entering new value in the text-box after pressing '=' my code is this
<title>Calculator</title>
<script>
var v = 0 ;
var operator = '';
function calc(obj){
if (obj.value == '+' || obj.value == '-' || obj.value == '*' || obj.value == '/' ){
v = document.getElementById("text_field").value;
operator = obj.value;
document.getElementById("text_field").value = '';
}
else if (obj.value == '='){
if (operator == '+')
{
document.getElementById("text_field"). value = v + document.getElementById("text_field").value ;
}
if (operator == '-')
{
document.getElementById("text_field").value = v - document.getElementById("text_field").value ;
}
if (operator == '*')
{
document.getElementById("text_field").value =v * document.getElementById("text_field").value ;
}
if (operator == '/')
{
document.getElementById("text_field").value = v / document.getElementById("text_field").value ;
}
}
else {
document.getElementById("text_field").value = document.getElementById("text_field").value + obj.value;
}
}
</script>
Use parseInt: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
for example:
parseInt(document.getElementById("text_field").value)

Javascript dashes in phone number

I tried to research the answer to this question but I'm lost. I am trying to make a one search bar that automatically puts a dash in the phone number. I've solved that.
The next part is the challenging part. How can I make it always do XXX-XXX-XXXX, even if the characters pasted were something like 555 555 1212 or 555---555-1212, where it will only reel back the number and output with 555-555-1212. It shouldn't count the spaces or extra dashes as a character.
I found: http://www.jotform.com/answers/15202-can-I-add-script-to-my-form-that-will-automatically-add-hyphens-in-between-the-3-digit-area-code-and-also-the-3-digit-prefix
I changed it just a bit by adding:
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
<input id="input_4" class="form-textbox" maxlength="15" name="atn" size="25" onBlur='addDashes(this)' />
Right now, this works only if the user puts 5555555555 and automatically turns it into 555-555-5555. I'm trying to figure out how to take something like 5-55555-5555 and turn it into 555-555-5555. Currently, it makes it 5-5-555-5-5555.
See my dilemma? lol. It can't be php or any server side scripting as this must be able to run on a desktop.
Resolution:
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.replace(/\D/g, '');
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
First, clean your input by deleting all chars that are not numbers (ref.: Regex to replace everything except numbers and a decimal point)
Then, you put your dashes.
function addDashes(f)
{
f_val = f.value.replace(/\D[^\.]/g, "");
f.value = f_val.slice(0,3)+"-"+f_val.slice(3,6)+"-"+f_val.slice(6);
}
I have a strong tendency to treat phone numbers as a straight string of 10 digits with no formatting (so I can apply formatting to them on-the-fly, as needed and so searching and comparison is simpler), although that may change if I ever have to deal with international phone numbers. If all you're dealing with is US phone numbers, this will work nicely (formats it as it's typed):
function addDashes(f) {
var r = /(\D+)/g,
npa = '',
nxx = '',
last4 = '';
f.value = f.value.replace(r, '');
npa = f.value.substr(0, 3);
nxx = f.value.substr(3, 3);
last4 = f.value.substr(6, 4);
f.value = npa + '-' + nxx + '-' + last4;
}​
Here's a fiddle: http://jsfiddle.net/EYuk5/
transform with string method replace
let phone = '0884332212'.replace(/^(\d{3})(\d{3})(\d{4})/, '$1-$2-$3')
console.log(phone)
// => 088-433-2212
I did this
function addDashesToNumber(number){
const numWithoutDashes = number.replace(/[^0-9]/g, '')
if(numWithoutDashes.length > 10) return number.slice(0, -1)
const dashPlaces = [3, 6]
return numWithoutDashes
.split('')
.reduce((acc, curr, i) => dashPlaces.includes(i) ? [...acc, '-', curr] : [...acc, curr], [])
.join('')
}
Try this:
function dashedNumber(value){
const afterIndices = [3,6,8];
const length = value.length;
let newValue = ''
for(let i=0; i<length; i++){
if(afterIndices.includes(i))
newValue+='-'
newValue+=value[i];
}
return newValue;
}
Here's a fiddle: https://jsfiddle.net/v9gq5jkw/.
<input id="phone">
function phone_formatting(ele, restore) {
var new_number,
selection_start = ele.selectionStart,
selection_end = ele.selectionEnd,
number = ele.value.replace(/\D/g, '');
if (number.length > 2) {
new_number = number.substring(0, 3) + '-';
if (number.length === 4 || number.length === 5) {
new_number += number.substr(3);
} else if (number.length > 5) {
new_number += number.substring(3, 6) + '-';
}
if (number.length > 6) {
new_number += number.substring(6);
}
} else {
new_number = number;
}
ele.value = (new_number.length > 12) ? new_number.substring(0, 12) : new_number;
if (new_number.slice(-1) === '-' && restore === false &&
(new_number.length === 8 && selection_end === 7) ||
(new_number.length === 4 && selection_end === 3)) {
selection_start = new_number.length;
selection_end = new_number.length;
} else if (restore === 'revert') {
selection_start--;
selection_end--;
}
ele.setSelectionRange(selection_start, selection_end);
}
function phone_number_check(field, e) {
var key_code = e.keyCode,
key_string = String.fromCharCode(key_code),
press_delete = false,
dash_key = 189,
delete_key = [8, 46],
direction_key = [33, 34, 35, 36, 37, 38, 39, 40],
selection_end = field.selectionEnd;
if (delete_key.indexOf(key_code) > -1) {
press_delete = true;
}
if (key_string.match(/^\d+$/) || press_delete) {
phone_formatting(field, press_delete);
} else if (direction_key.indexOf(key_code) > -1) {} else if (dash_key === key_code) {
if (selection_end === field.value.length) {
field.value = field.value.slice(0, -1)
} else {
field.value = field.value.substring(0, (selection_end - 1)) + field.value.substr(selection_end)
field.selectionEnd = selection_end - 1;
}
} else {
e.preventDefault();
phone_formatting(field, 'revert');
}
}
document.getElementById('phone').onkeyup = function(e) {
phone_number_check(this, e);
}
Beside adding dashes, you will need to deal with the position of the cursor, especially in case of deletion.
This AMD module does exactly that: https://github.com/whenyoubelieve2014/us-telephone-input

Categories