Reputation: 101
So I'm trying to make a simple calculator with only 5 buttons:
- '1'
- '2'
- '+'
- '='
- '0'.
The idea is to make it work like a proper calculator (after I figure out this logic I would make a normal calculator). I understand the reset button ('0') only. The hard part for me to figure out is '+' and '='.
I want to make it so that '=' gives a result of two summed (or some other action but in this case I only have '+' button) up general numbers (so it works later on when I add other numbers).
I know that there are calculator tutorials online but I want to figure it out on this simple example.
You don't even need to write out the code for me (or you can write out some code) and maybe only explain the logic that I need to follow.
import { useState } from "react";
export default function App() {
const [currentState, setCurrentState] = useState(0);
return (
<div>
<button
className="btn"
name="1"
value={1}
onClick={() => setCurrentState(1)}
>
1
</button>
<button
className="btn"
name="2"
value={2}
onClick={() => setCurrentState(2)}
>
2
</button>
<button className="btn" name="+" onClick={() =>
setCurrentState("+")}>
+
</button>
<button
className="btn"
name="="
onClick={() => setCurrentState()}
>
=
</button>
<button
className="btn"
name="reset"
value={0}
onClick={() => setCurrentState(0)}
>
0
</button>
<h2>{currentState}</h2>
</div>
);
}
Upvotes: 0
Views: 1119
Reputation: 49
I made a simple calculator using a different approach, I hope my idea can help you.
I made a class to do all operations, and use the front objects just to send commands. One entering command (setToken), where I send a tag for the button pressed. Then, all logic is centralized in the class, setting a result property (getValue). The front do a very simple task, only send buttons tag and read result, writting the output.
I will not go into details here, because maybe its not the case here. My advice here is to make a class to focus only in the operations logic, so you can easily improve more funcions and buttons without break the basic working.
Sincerely, I dont know the logic people usually do, its just my macro schema.
In a very basic overview, my logic is using a tokenization flow, doing decisions according the token send. For example, while digits, mounting the entering number, if operator, save digit into a variable and operator into another. And so on, if a second operator, when second number saved, do the according operation and update the output property.
I hope it can help you. I am still improving my calculator, not good yet to show. It is in Android Java.
In time, I use a state variable too, to know if its in a digiting number state, or an operator pressed at last. It helps to know what to do next.
Good luck!
Upvotes: 0
Reputation: 33739
Having a conceptual understanding of the fundamental differences between infix notation and postfix notation will help you tremendously in solving your problem.
You have two input types right now:
0
, 1
, 2
)+
)and one action:
=
)Having only 3 values for operand input and one operation type might seem like it would make creating a calculator simpler, but that's not really the case: especially if you ever want to expand your calculator (as you stated in your question). Adding a few more buttons and operations is actually the easy part. You still have to implement all of the same logic.
If you want to take a shortcut to have a calculator that can only add values which are replaced with each button press, then that would be simpler because you'll be hardcoding some behavior, but you'll be skipping some very core parts that you'll encounter later when expanding it, like:
That being said, if you want to take the simple route of hardcoding at first in order to see something working, then you're most of the way there! You just need to add a bit more state to get things working:
body {
font-family: monospace;
font-size: 4rem;
}
button {
border: 2px solid hsl(0, 0%, 65%);
font-family: monospace;
font-size: 2rem;
height: 3rem;
width: 3rem;
}
button:focus {
border-color: hsl(0, 0%, 0%);
}
.buttons {
display: flex;
gap: 0.5rem;
}
<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="react">
const {useState} = React;
function Button (props) {
return <button onClick={props.onClick}>{props.text}</button>;
}
function Example () {
const [operands, setOperands] = useState([0, 0]);
const [activeIndex, setActiveIndex] = useState(0);
const setValue = (value, index = activeIndex) => {
setOperands(arr => arr.map((n, i) => i === index ? value : n));
};
const add = () => {
setOperands(([n1, n2]) => [n1 + n2, 0]);
setActiveIndex(0);
};
const handlePlus = () => {
if (activeIndex === 0) setValue(operands[0], 1);
setActiveIndex(1);
};
return (
<div>
<div>{operands[activeIndex]}</div>
<div className="buttons">
<Button onClick={() => setValue(0)} text="0" />
<Button onClick={() => setValue(1)} text="1" />
<Button onClick={() => setValue(2)} text="2" />
<Button onClick={handlePlus} text="+" />
<Button onClick={add} text="=" />
</div>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
</script>
Upvotes: 1
Reputation: 16
create a list of buttons from 0 to 9 and give number as key and do the same for the operators
on click of the buttons get the key value and check its type, if it is number you can keep on constructing your number as string (ex:'4567') till you get the operator once you get the operator store it in a variable and keep on constructing the second number once you receive second operator or equals symbol you can pass the two number string to the corresponding functions like Addition Subtraction or Multiplication and store result in a state and you can keep on doing the same
Upvotes: 0
Reputation: 1
Here is my logic:
Instead of modifying currentState
every time you press a button, you could save the result of the calculation in a state called currentValue
.
You can save the numbers and operations in three global variables, num1
, num2
, and operation
. Then when you press the equal button, you can call setCurrentValue
to save the newly calculated value in currentValue
.
If you want to continue the calculation, you can save the value of num1
to be equal to currentValue
, reset the value of num2
and operation
, then wait for the next input.
Hope it makes sense!
Upvotes: 0