Task: Create a table of values ​​of the function y = f (x) on the interval [n; m] with step k

Actually the question arises in the moment. How to enter f (x). For the formula itself (for example, x-2) is a string, and the value of Y is a number. those. Through the scanner enter all the values ​​of n, m, k and the formula "x-2" or any other. And in the code, this formula is used to calculate the value of Y.

while(x<=rm){ y=x-5; System.out.println("x = " +x+" y = "+ y); x=x+rk; } 

In this case, I have a formula entered initially "y = x-5" (second line, entered clumsily, directly into the code), and I need the program to read the one that I enter through the scanner.

upd. After a large number of read and tested, I want to add that entered through the scanner is Tsislov values, the letter X and the signs of arithmetic calculations ("+", "-", "/", "*").

  • take a look here - TimurVI
  • one
    it became better, but X does not want to capture yet. But insight is near. - Masha

1 answer 1

The decision of a lazy person looks like this:

 import javax.script.*; public class Eval { public static void main (String[] args) throws Exception { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName("nashorn"); engine.put("x", 1); System.out.println(engine.eval("x * 2 + 1")); } } 

In Java, there is a full-fledged JavaScript engine ( in Russian ) that does an excellent job with calculating arbitrary mathematical expressions (and not only them).

The decision of the person to whom the described task arrived in the form of laboratory work or homework looks more complicated. The teacher most likely expects you to sort the input string into tokens (variable, operator, number), translate it into a reverse Polish record , and then calculate it using a stack machine ( one , two ).

  • Thanks for the answer) The problem is not from the teacher, but from these of your Internet :) - Masha