Java Taschenrechner mit mehreren Nummern und Operatoren?
Hey.
Ich möchte einen Taschenrechner in Java programmieren. (Konsolen applikation) Man soll es so auf einmal eingeben können: 5+7-1*10/7. Ohne Punkt vor Strich. Einfach nach der Reihe. Meine Frage ist nun wie ich da am besten Vorgehe
The most difficult task is the “tokenization”, i.e. the dismantling of the input in operands (numbers) and operators (+, -, *, /).
There are different approaches for this. One is regular expressions, which you should learn as a developer anyway (even if some people think that is not reasonable for beginners). With such a simple “language” as in your task, this can be relatively easy: e.g. you can first of all Remove spaces and then on transitions between numbers and letters splinters leave. You can do this with sites like https://regex101.com/ also test well outside the program.
Alternatively, you can make this on foot: you go sign for characters through the string and decide what number and what operator is. This is very simple, but it will cost you a few more lines.
Professionals use their own parser generators like ANTLAL, with which very much more complicated expressions are well represented. It would be exaggerated.
Once you have made this separation, the rest is very simple: convert numbers strings into numbers, and perform the desired computing operation depending on the operator.
On foot I could go through the string with a For loop. But if I have “32+1-6” then there are 3 and 2 together. So, 32.
I could look at each number with the loop and if an operator comes then I left + right (from operator)
Or I could just filter everything out with Regex and then go through
The eval functions If you are interested in carrying out mathematical formulas to be entered at runtime, you hardly get past:
Keep in mind that eval radios are able to execute any user inputs at runtime. If a string is executed, you must check that it does not contain any inadmissible commands.
If you only use the program for your own needs, such safety precautions can of course be dispensed with.
Technically, a mathematical formula entered as a string is executed exactly as if you had entered it in the source code of your program. Eval is always slower than compiled code, as it has to be interpreted at runtime/ JITcompiled.
Aside from the security implications: modern JDKs (from 15) no longer come with a JS-Runtime. Thus, all solutions that require this are no longer viable.