How to take math equations in an Input box and have the equation calculated and the answer printed in the console?

Viewed 29

So I am creating a project on P5JS, where you type in a math equation into an input box for example: 56 + 14, then after I click a calculate button, it prints the answer (70) to this equation in the console and the same for divide, multiply and subtract which also is printed in the console. My code so far is attached. So far it print the equation that is inputed into the input box, however it is not actually calculating the answer so how can I fix?

function setup() {
  createCanvas(850, 800);

    PLUSX = createButton("+");               //  Create Button
    PLUSX.position(320, 380);  
    PLUSX.size(80, 30);
  
    SUBTRACTX= createButton("-");            //  Create Button
    SUBTRACTX.position(320, 340);
    SUBTRACTX.size(80, 30);
  
    MULTIPLYX= createButton("×");            //  Create Button
    MULTIPLYX.position(320, 300);
    MULTIPLYX.size(80, 30);
  
    DIVIDEX= createButton("×");              //  Create Button
    DIVIDEX.position(320, 260);
    DIVIDEX.size(80, 30);
  
    ROOTX= createButton("√");                //  Create Button
    ROOTX.position(450, 260);
    ROOTX.size(80, 30);
  
    SQUAREX= createButton("x²");             //  Create Button
    SQUAREX.position(450, 300);
    SQUAREX.size(80, 30);
  
    PISYMBOLX= createButton("π");            //  Create Button
    PISYMBOLX.position(450, 340);
    PISYMBOLX.size(80, 30);
  
    PERCENTAGEX= createButton("%");          //  Create Button
    PERCENTAGEX.position(450, 380);
    PERCENTAGEX.size(80, 30);
    
    INPUT = createInput();                   //  Create Input
    INPUT.position(270, 200);
    INPUT.size(300);

    NUMEQUALX = createButton('=');                   //  Create Input
    NUMEQUALX.position(270, 460);
    NUMEQUALX.size(300)
    NUMEQUALX.mousePressed(answer);
}



var PLUSX;
var SUBTRACTX;
var MULTIPLYX;
var DIVIDEX;
var ROOTX;
var SQUAREX;
var PISYMBOLX; 
var PERCENTAGEX;  
var INPUT;  
var NUMEQUALX;


function draw() {
  background(255);

textFont("This is a sans-serif font");            
text(" Calculator", 10, 40);                
fill(64, 64, 64);              
textSize(30);  

}

function answer()                     //  Function Answer

    {
      
      
  ANS = INPUT.value();                         //  INPUT Value
  console.log("ANSWER: " + ANS);               //  Log In Console As ANS

  
      
      
      
      
      
      
      
      
      
      
    }
0 Answers
Related