Skip to content

Input Validation and Error Handling #1165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Calculator/sushil-2803/use.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ function number_handler(event) {
var currentString = input.innerHTML;
var lastChar = currentString[currentString.length - 1];

// enhancement added here: Prevent multiple decimals in a single number
if (event.target.innerHTML === '.' && currentString.includes('.')) {
console.log("Multiple decimal points not allowed in a single number.");
return;
}

// if result is not diplayed, just keep adding
if (resultDisplayed === false) {
input.innerHTML += event.target.innerHTML;
Expand Down Expand Up @@ -41,6 +47,12 @@ function operator_handler(event) {
var currentString = input.innerHTML;
var lastChar = currentString[currentString.length - 1];

// enhancement added here: Prevent consecutive operators
if (lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷") {
input.innerHTML = currentString.slice(0, -1) + event.target.innerHTML;
return;
}

// if last character entered is an operator, replace it with the currently pressed one
if (lastChar === "+" || lastChar === "-" || lastChar === "x" || lastChar === "÷") {
var newString = currentString.substring(0, currentString.length - 1) + event.target.innerHTML;
Expand Down Expand Up @@ -122,6 +134,12 @@ function output(){
// first we replace all the numbers and dot with empty string and then split
var operators = inputString.replace(/[0-9]|\./g, "").split("");

// enhancement added here: Division by zero check
if (operators.includes("÷") && numbers[numbers.indexOf("÷") + 1] == 0) {
alert("Error: Division by zero is undefined.");
return;
}

console.log(inputString);
console.log(operators);
console.log(numbers);
Expand Down