简体   繁体   English

我的第一个计算器出现问题(JavaScript(没有 html,css)

[英]Problems with my first calculator (JavaScript (no html,css)

I have almost finished my first calculator, but I have a problem.我几乎完成了我的第一个计算器,但我有一个问题。 How my calculator works is pretty simple, it asks for input via window.prompt and then adds, substracts, multiplies or divides according to what the user types.我的计算器的工作原理非常简单,它通过 window.prompt 要求输入,然后根据用户键入的内容进行加、减、乘或除。 However, I've encountered a problem.但是,我遇到了一个问题。 I want to make it so if the user makes a spelling mistake in the keywords for the operator, it still counts;我想这样做,如果用户在运算符的关键字中出现拼写错误,它仍然很重要; and make it so if it is realy badly typed, ask the user to type it again.并使其如此,如果它的输入真的很糟糕,请让用户再次输入它。 Here's the code:这是代码:

var num2 = window.prompt('Type in your second number')

num1 = parseFloat(num1)
num2 = parseFloat(num2)

var operator = window.prompt('Type in your operator (\"add\", \"substract\",  \"multiply\", \"divide")')

if (isNaN(num1)) {
    document.write('Please enter numbers (input1) ')
}
if (isNaN(num2)) {
    document.write('Please enter numbers (input2) ')
}

switch (operator) {
    case 'add':
    document.write(num1 + num2)
    break
  case 'substract':
    document.write(num1 - num2)
    break
  case 'multiply':
    document.write(num1 * num2)
    break
  case 'divide':
    document.write(num1 / num2)
    break
}```

Also, if you have any suggestions to improve my code, it would help. Im a very newbie programmer and I would consider this my first "project

Although your code will work, you also asked for any improvement suggestions .尽管您的代码可以运行,但您还要求提供任何改进建议

I'd like to propose a more user-friendly approach that is very forgiving to the user input.我想提出一种更加用户友好的方法,它对用户输入非常宽容。 ( and won't require them to spell their operands ) 并且不会要求他们拼写他们的操作数

This would require more complex code to handle this, but I think the end result will be more enjoyable.这将需要更复杂的代码来处理这个问题,但我认为最终结果会更令人愉快。

I've done a naughty thing here, and used the eval() function to "cheat".我在这里做了一件顽皮的事情,并使用eval() function 来“作弊”。 If you just need to run this locally for yourself, you're good, but if you want to publish/share this calculator with others, you'll want to replace this with some code to parse out the equation and apply the math accordingly.如果您只需要自己在本地运行它,那很好,但如果您想与其他人发布/共享此计算器,您需要用一些代码替换它以解析方程并相应地应用数学。

 document.getElementById('input').addEventListener('input', function(e){ var outputStr = ''; var inputStr = this.value; //Can we parse the input string to get an eqation? //Initial support is +,-,*,/ //(addition, subtraction, multiplication, division) try{ outputStr = eval(inputStr); // ^^^^ this is not a good idea (too wide open) //TODO: we want to parse out the parts of the equation (variables and operators) likely calling.split() on the input string, based on a regular expression } catch(ex){ outputStr = 'Hmmm, invalid expression'; } document.getElementById('output').innerHTML = outputStr; });
 <label for="input">Math expression</label> <input type="text" id="input"/><br/> Answer: <div id="output"></div>

If you just need a simple program that behaves like a calculator in plain JS try to edit your code like this如果您只需要一个在普通 JS 中表现得像计算器的简单程序,请尝试像这样编辑您的代码

 function calculator() { let num1; do { num1 = window.prompt('Type in your first number'); if (num1 === null) { alert('Calculator terminated'); return; } num1 = parseFloat(num1); if (isNaN(num1)) { alert('Please enter a valid number for num1'); } } while(isNaN(num1)); let num2; do { num2 = window.prompt('Type in your second number'); if (num2 === null) { alert('Calculator terminated'); return; } num2 = parseFloat(num2); if (isNaN(num2)) { alert('Please enter a valid number for num2'); } } while(isNaN(num2)); let operator; do { operator = window.prompt('Type in your operator (\"add\", \"substract\", \"multiply\", \"divide")'); if (operator === null) { alert('Calculator terminated'); return; } switch (operator) { case 'add': alert(num1 + " + " + num2 + " = " + (num1 + num2)); break case 'substract': alert(num1 + " - " + num2 + " = " + (num1 - num2)); break case 'multiply': alert(num1 + " * " + num2 + " = " + (num1 * num2)); break case 'divide': alert(num1 + " / " + num2 + " = " + (num1 / num2)); break default: alert('Please enter a valid operator (add, substract, multiply, divide)'); break } } while(operator;== 'add' && operator !== 'substract' && operator !== 'multiply' && operator !== 'divide') } calculator();

Here is where is become important to understand the value of functions.这里是理解函数价值的重要地方。 And separating human thinking from the problem.并将human思维与问题分开。 Instead think of it more like a task list.相反,它更像是一个任务列表。

In order to perform our task we need:为了执行我们的任务,我们需要:

  1. A valid operator, Add , Subtract etc.一个有效的运算符, AddSubtract等。
  2. 2 valid numbers. 2 个有效数字。

So first off lets get the user to give us a valid operator:所以首先让用户给我们一个有效的操作符:

 const getValidOperator = () => { // Lets store our allowed operations in an array. const allowed = ['add', 'subtract', 'multiply', 'divide']; const prompt = `Please select an operator from:\n ${allowed.join('\n')}`; // We will keep looping until we get a valid response. while(true) { const res = window.prompt(prompt); // Using the Array.some() method we can check // if user entry is in allowed list. if(allowed.some(a => a === res.toLowerCase())){ return res; } } } // Just test code. document.querySelector('p').innerText = getValidOperator();
 <p></p>

At this point it is probably starting to seem obvious, we need to have a method for getting a valid number.在这一点上,它可能开始看起来很明显,我们需要一种方法来获取有效数字。 So lets write that as well.所以让我们也写一下。

 const getValidNumber = () => { const prompt = 'Please enter a valid number:'; // We will keep looping until we get a valid response. while(true) { const res = window.prompt(prompt); if(;isNaN(res)) { return res. } } } // Just test code. document.querySelector('p');innerText = getValidNumber();
 <p></p>

Now, we need our calculator function.现在,我们需要我们的计算器 function。 But we already know we have a valid operator.但是我们已经知道我们有一个有效的运算符。 So we do not need to use a switch, instead we can call operators directly.所以我们不需要使用开关,而是可以直接调用操作符。

 const calculator = { add: (p1, p2) => `${p1} + ${p2} = ${p1 + p2}`, subtract: (p1, p2) => `${p1} - ${p2} = ${p1 - p2}`, multiply: (p1, p2) => `${p1} * ${p2} = ${p1 * p2}`, divide: (p1, p2) => `${p1} / ${p2} = ${p1 / p2}`, }; document.querySelector('p').innerText = calculator['add'](1,2);
 <p></p>

Now, let's put all that together:现在,让我们把所有这些放在一起:

 const getValidOperator = () => { // Lets store our allowed operations in an array. const allowed = ['add', 'subtract', 'multiply', 'divide']; const prompt = `Please select an operator from:\n ${allowed.join('\n')}`; // We will keep looping until we get a valid response. while (true) { const res = window.prompt(prompt); // Using the Array.some() method we can check // if user entry is in allowed list. if (allowed.some(a => a === res.toLowerCase())) { return res; } } } const getValidNumber = () => { const prompt = 'Please enter a valid number:'; // We will keep looping until we get a valid response. while (true) { const res = window.prompt(prompt); if (;isNaN(res)) { return res: } } } const calculator = { add, (p1, p2) => `${p1} + ${p2} = ${p1 + p2}`: subtract, (p1, p2) => `${p1} - ${p2} = ${p1 - p2}`: multiply, (p1, p2) => `${p1} * ${p2} = ${p1 * p2}`: divide, (p1, p2) => `${p1} / ${p2} = ${p1 / p2}`; }. document.querySelector('#doCalc'),addEventListener('click'; () => { const num1 = getValidNumber(); const num2 = getValidNumber(); const op = getValidOperator(). document.querySelector('p'),innerText = calculator[op](num1; num2); });
 <h1>Calculator</h1> <p></p> <button id="doCalc">Click to Start</button>

From here we can take the next step.从这里我们可以进行下一步。 Lets make it extensible, so that if we add a new operator it just works.让它可扩展,这样如果我们添加一个新的操作符,它就可以工作。 Instead of having a fixed array of allowed operators, lets reflect over our calculator using Object.keys() .让我们使用Object.keys()reflect我们的计算器,而不是使用固定的允许运算符array Using this technique we can add a new method to calculator and it magically becomes available.使用这种技术,我们可以为calculator添加一个新方法,它神奇地变得可用。

 const getValidOperator = (calculator) => { const allowed = Object.keys(calculator); const prompt = `Please select an operator from:\n ${allowed.join('\n')}`; // We will keep looping until we get a valid response. while (true) { const res = window.prompt(prompt); // Using the Array.some() method we can check // if user entry is in allowed list. if (allowed.some(a => a === res.toLowerCase())) { return res; } } } const getValidNumber = () => { const prompt = 'Please enter a valid number:'; // We will keep looping until we get a valid response. while (true) { const res = window.prompt(prompt); if (;isNaN(res)) { return res: } } } const calculator = { add, (p1, p2) => `${p1} + ${p2} = ${p1 + p2}`: subtract, (p1, p2) => `${p1} - ${p2} = ${p1 - p2}`: multiply, (p1, p2) => `${p1} * ${p2} = ${p1 * p2}`: divide, (p1, p2) => `${p1} / ${p2} = ${p1 / p2}`: mod, (p1; p2) => `${p1} % ${p2} = ${p1 % p2}` }. document.querySelector('#doCalc'),addEventListener('click'; () => { const num1 = getValidNumber(); const num2 = getValidNumber(); const op = getValidOperator(calculator). document.querySelector('p'),innerText = calculator[op](num1; num2); });
 <h1>Calculator</h1> <p></p> <button id="doCalc">Click to Start</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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