I have made a calculator but the problem is that I can't make it so that there can't be two operators in a row, for example (4*2++).
The user shouldn't be able to press two operators in a row. My fix was that if the user puts in a "+", i would look for the last character in my >calculation> (holds all the input numbers and operators) string and change that operator according to
which operator the user presses next. Example, if the user puts in, 4*2+, then presses "-", the <calculation> is changed to, 4*2- . This somehow doesn't work. Is there anything I'm missing?
Well, first of all you shouldn't use the == operator to compare whether the contents of two String objects are equal. The == operator compares whether the references point to the same String object, whereas it's easy for two different String objects to contain the same value.
But there's no need to use String objects at all there. I would suggest using char variables instead; a char is a primitive value so the == operator works in the obvious way. Just remember that a character literal is surrounded by single quotes.
I've commented out the third line of code because it has so many problems. It looks like you wanted to replace the + sign by another + sign, which is already a problem, so getting into the other problems with the way you tried to do that would be a waste of time. What did you actually intend to do there?
(The whole code block might be off-course anyway -- you claim to be looking for two operators in a row, but your code is just looking for a + sign at the end. How does that help?)
And you used a method called setOnClickListener which isn't part of the standard Java API. It's part of the Android API, though. Are you writing an Android app? If so then we should move this thread to the Android forum. Let us know.
posted 1 year ago
The third line is looking for the last character and if it's a "+" replace it with a "+" so it doesn't add the plus signs.
This is one of those times when separation of concerns really helps. Parsing user input should be a separate concern from obtaining user input. Mixing those two concerns in one method really makes your design more brittle, more difficult to test, and less cohesive.
The user can only use an operator once, followed by numbers. How do I do this?
Well, earlier I asked whether you were writing a Java app or an Android app. You haven't answered yet. If it's Java then you're going to have to explain where the setOnClickListener method and the View class come from, as they aren't part of the standard Java API.