The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

AS3 Calculator help needed

littlea5hlittlea5h Registered User regular
edited March 2012 in Help / Advice Forum
Hi. So I am in the process of creating a calculator entirely through actionscript, nothing is on the staging area. So far i am up to performing the calculations. However i seem to be having problems. A sample of my code is shown below:
import flash.events.MouseEvent;

var btn:Array = new Array();

for(var i = 0; i < 10; i++) {
	var myBtn:Btn = new Btn();
	myBtn.y = 15;
	myBtn.x = i * 100 + 15;
	myBtn.width = 48;
	myBtn.height = 48;
	myBtn.buttonMode = true;
	myBtn.mouseChildren = false;
	myBtn.num = Number(i);
	myBtn.caption.text = String (i);
	addChild(myBtn);
	btn.push(myBtn);
	btn[i].addEventListener(MouseEvent.CLICK,pressNumber);//EVENT TO ADD NUMBERS TO DISPLAY	
		
}
btn[0].y += 370;
btn[0].x += 10;

btn[1].y += 310;
btn[1].x += -90;

btn[2].y += 310;
btn[2].x += -130;

btn[3].y += 310;
btn[3].x += -170;

btn[4].y += 250;
btn[4].x += -390;

btn[5].y += 250;
btn[5].x += -430;

btn[6].y += 250;
btn[6].x += -470;

btn[7].y += 190;
btn[7].x += -690;

btn[8].y += 190;
btn[8].x += -730;

btn[9].y += 190;
btn[9].x += -770;

//OPERATORS//
var operators:Array = new Array();
for(var io:int = 0; io < 6; io++) {
	var opBtn:Btn_operator = new Btn_operator();
	opBtn.width = 48;
	opBtn.height = 48;
	opBtn.buttonMode = true;
	opBtn.mouseChildren = false;
	opBtn.caption_op.text = String (".");
	addChild(opBtn);
	operators.push(opBtn);	
	operators[io].addEventListener(MouseEvent.CLICK, pressOperator);//EVENT TO ADD OPERATORS TO DISPLAY
}

//ADD DOT
var dot:Btn_dot = new Btn_dot();
	dot.width = 48;
	dot.height = 48;
	dot.buttonMode = true;
	dot.mouseChildren = false;
	dot.caption_op.text = String (".");
	addChild(dot);

dot.y += 383;
dot.x += 78;
dot.addEventListener(MouseEvent.CLICK, addDot);//EVENT TO ADD DOT TO DISPLAY

//BACKSPACE
var goBack:Btn_backspace = new Btn_backspace();
	goBack.width = 48;
	goBack.height = 48;
	goBack.buttonMode = true;
	goBack.mouseChildren = false;
	goBack.caption_op.text = String ("<--");
	addChild(goBack);

goBack.y += 203;
goBack.x += 256;
goBack.addEventListener(MouseEvent.CLICK, backSpace);//EVENT TO GO BACK SPACE IN DISPLAY

//BACKSPACE
var clearAll:Btn_clear = new Btn_clear();
	clearAll.width = 48;
	clearAll.height = 48;
	clearAll.buttonMode = true;
	clearAll.mouseChildren = false;
	clearAll.caption_op.text = String ("C");
	addChild(clearAll);
	

clearAll.y += 323;
clearAll.x += 256;
clearAll.addEventListener(MouseEvent.CLICK, clearFields);//EVENT TO GO BACK SPACE IN DISPLAY

operators[0].y += 383;
operators[0].x += 138;
operators[0].caption_op.text = String("=");

operators[1].y += 383;
operators[1].x += 198;
operators[1].caption_op.text = String("/");

operators[2].y += 323;
operators[2].x += 198;
operators[2].caption_op.text = String("*");

operators[3].y += 263;
operators[3].x += 198;
operators[3].caption_op.text = String("-");

operators[4].y += 203;
operators[4].x += 198;
operators[4].caption_op.text = String("+");

operators[5].y += 263;
operators[5].x += 256;
operators[5].caption_op.text = String("-/+");


//VARIABLE HANDLE OPERATION NOT BUTTON
var operate:String;

//HANDLE FIRST AND SECOND VALUE
var num1:Number;
var num2:Number;

//grouping all buttons in function


//display_txt.text = "0";
//DISPLAYING NUMBERS IN DISPLAY
//var numberEntered:String ="";
function pressNumber(e:MouseEvent):void{
	       display_txt.appendText(e.target.num);
}

//DISPLAY OPERATORS
function pressOperator(event:MouseEvent):void{
	var operatorEntered:String;
	display_txt.appendText(event.currentTarget.caption_op.text);
	//CHECKING FOR VALUES AND STORING NUMBERS
	if(isNaN(num1)){
		//CONVERT STRING TO NUMBER
		num1=Number(display_txt.text);
		operate = operatorEntered;
		display_txt.text = "";
        trace(num1,isNaN(num1)); // if this outputs some number and true, display_txt an html enabled textfield, has kerning enabled or is a multiline textfield.  fix that.
	}
	else if(isNaN(num2)){
		num2 = Number(display_txt.text);
		trace(num1,isNaN(num2)); // if this outputs some number and true, display_txt an html enabled textfield, has kerning enabled or is a multiline textfield.  fix that.
		performCalculation();
		operate = operatorEntered;
	}
	}


//CLEARS DISPLAY AREA
function clearFields(event:MouseEvent):void{
	display_txt.text = "";
	num1=NaN;
	num2=NaN;
	}

//ADDS DECIMAL PLACE
function addDot(event:MouseEvent):void{
	if(event.target.num == Number(display_txt.text))
	{
	display_txt.text = "0";
	}
	if (display_txt.text.indexOf(".")==-1){
		display_txt.appendText(".");
	}
	
	}
//BACKSPACE DISPLAY AREA
function backSpace(e:MouseEvent):void{
	var temp_str:String = display_txt.text;
	display_txt.text = temp_str.substr(0, (temp_str.length-1)); // Get rid of last character in the string, which in this case is the phantom \r or \n character
}

function performCalculation():void{
	
	switch (operate){
	case "multiply":
		num1*=num2;
	break;
	case "divide":
		num1/=num2;
	break;
	case "subtract":
		num1-=num2;
	break;
	case "add":
		num1+=num2;
	break;
		default:
	break;
}
//now that we found out the result
//let's display on the window
display_txt.text=String(num1);
num2=NaN;
	
}

It doesn't seem to be performing the calculations and in the code shown below, it is meant to be calling the function to perform the calculations but it doesn't seem to be doing that anymore and when i try to trace num1 it outputs as NaN when it is meant to show the button last pressed when i click on a operator.
function pressOperator(event:MouseEvent):void{
   var operatorEntered:String;
   display_txt.appendText(event.currentTarget.caption_op.text);
   //CHECKING FOR VALUES AND STORING NUMBERS
   if(isNaN(num1)){
      //CONVERT STRING TO NUMBER
      num1=Number(display_txt.text);
      operate = operatorEntered;
      display_txt.text = "";
      trace(num1);
   }
   else if(isNaN(num2)){
      num2 = Number(display_txt.text);
      performCalculation();
      operate = operatorEntered;
   }
   }

littlea5h on

Posts

  • MalgarasMalgaras Registered User regular
    edited March 2012
    Well, I've never used actionscript, but a couple things stand out to me.

    In pressOperator, you create the variable operatorEntered but never initialize it to anything. Then, you take take display_txt, append the symbol for the operator to it, and then try to parse it back out as a number. I'm assuming what you want to do is append that to operatorEntered instead. because the next thing you do is set operate to the value of operatorEntered(which currently never gets initialized) and then send that to a switch statement later to check for an operator. Currently, your default in performCalculation is always going to fire because you are switching on a string set to nothing.

    I assume you want something more like this (you may need to fix some syntax. Like I said, I've never used actionscript);

    Here is our pressOperator method. Seems pretty bare doesn't it? We will get back to this and add some more later, but for now, all we want to do is append the operator to the screen and set the operate variable so we can check what operation to do later.
    function pressOperator(event:MouseEvent):void{
       operate = event.currentTarget.caption_op.text);
       display_txt.appendText(event.currentTarget.caption_op.text);
    }
    

    Now, since where DO we want to create our numbers? We want to add a digit when a user presses a button.

    To do this, first we need a variable to hold our current number.
    var currentNumber:String = "";
    

    Then, when somone presses a number, add a digit.
    function pressNumber(e:MouseEvent):void{
        display_txt.appendText(e.target.num);
        currentNumber.append(e.target.num);
    }
    

    Now, what do we do when we want to move on to the next number? We want to store the current number and reset our string.
    function setNumber():void{
        if(isNan(num1){
            num1 = number(currentNumber) //if we haven't set our first number yet, set it.
        } else {
            num2 = number(currentNumber) //if 1 is set, set 2 instead
       }
       currentNumber = ""; //either way, reset our string for the next number
    }
    

    Now, how do we get our answer after all this? Let's go back to our pressOperator function and add some stuff.
    function pressOperator(event:MouseEvent):void{
       operate = event.currentTarget.caption_op.text);
       display_txt.appendText(event.currentTarget.caption_op.text);
       setNumber();
    
       if(!(isNan(num1)) || (isNan(num2))){ //if both num1 and num2 are defined
           performCalculation();
       }
    }
    
    The first bit is old, and you know what setNumber does now. What about the last bit? Essentially, if both numbers are set, we want to perform the operation on them and then store the result as num1. Since performCalculation does this, we can simply call it like before. Keep in mind, I guessed at the if statement syntax. That may or may not be correct in actionscript.

    Keep in mind this is far from complete, just a little help to get you going since you're stuck. Another issue you will run into is that you are assigning the value caption_op.text with the SYMBOL for the number, but then switching later on the WORD for the operator. You need to change the values and the switch both to the same set of strings or it will still never work even with the above issue fixed. Another issues is that your back and period keys will need to be fixed and your decimal key needs to also append to currentNumber. There may be lots of other things too. I didn't go over everything that thoroughly.

    Now, in all honesty, I would write this completely differently than your current implementation, but hopefully this will help you with your way. If you want an example of how I'd do it, I can provide some pseudocode if you really want it. Hope this helps. I'll check back in if you need more help.

    Malgaras on
    1tLJUH2O.png
  • littlea5hlittlea5h Registered User regular
    Thank you for taking the time out to go through the code and provide me with the advice. I will try and attempt it and update you. :-)
    An example of pseudo code could really be helpful. Thank you.

  • MalgarasMalgaras Registered User regular
    Well, I'll be gone for the rest of the day shortly. I'll see about putting something together tomorrow or Sunday. By the way, it occurs to me that the if statement is slightly incorrect in pressOperator. I'll let you figure out where. :P

    1tLJUH2O.png
  • littlea5hlittlea5h Registered User regular
    Ahh i am hitting brick walls now :cry:

  • MalgarasMalgaras Registered User regular
    What problems are you having?

    1tLJUH2O.png
  • littlea5hlittlea5h Registered User regular
    Well the good news is, i have my calculator performing operations, however the bad news there are a couple of flaws here and there :(

    1. Operator is allowed to be entered before a number and more than one operator is displayed, unsure how to use the replace function.
    2. When entering a new calculation the old one isn't replaced, however i would like to show the old calculation and make a new line for the next one
    3. The addDot function will only work with the first number but it doesn't recognise the dot in the calculation. It also doesn't automatically add the 0 when it is pressed before a number. It only lets me input it with the first number so i need it to work with the second number however i am not entirely sure that it calculates as a decimal. When i try 5.2 + 4 it outputs as a whole number instead 56. Here is the code i have:
    import flash.events.MouseEvent;
     
    var btn:Array = new Array();
    for (var i = 0; i < 10; i++) {
        var myBtn:Btn = new Btn();
    	myBtn.y = 15;
    	myBtn.x = i * 100 + 15;
    	myBtn.width = 48;
    	myBtn.height = 48;
        myBtn.buttonMode=true;
        myBtn.mouseChildren=false;
        myBtn.num=Number(i);
        myBtn.caption.text=String(i);
        addChild(myBtn);
        btn.push(myBtn);
        myBtn.addEventListener(MouseEvent.CLICK,pressNumber);
    }
    //EVENT TO ADD NUMBERS TO DISPLAY                                       ;
     
    btn[0].y += 370;
    btn[0].x += 10;
    
    btn[1].y += 310;
    btn[1].x += -90;
    
    btn[2].y += 310;
    btn[2].x += -130;
    
    btn[3].y += 310;
    btn[3].x += -170;
    
    btn[4].y += 250;
    btn[4].x += -390;
    
    btn[5].y += 250;
    btn[5].x += -430;
    
    btn[6].y += 250;
    btn[6].x += -470;
    
    btn[7].y += 190;
    btn[7].x += -690;
    
    btn[8].y += 190;
    btn[8].x += -730;
    
    btn[9].y += 190;
    btn[9].x += -770;
    
    //OPERATORS//
    //OPERATORS//
    var operatorSelected:Boolean;
    var operate:Array=new Array("÷","x","-","+");
    var operators:Array = new Array();
    for (var io:int = 0; io < 4; io++) {
        var opBtn:Btn_operator = new Btn_operator();
    	opBtn.width = 48;
    	opBtn.height = 48;
        opBtn.buttonMode=true;
        opBtn.mouseChildren=false;
        opBtn.op=Number(operators);
        addChild(opBtn);
        operators.push(opBtn);
        opBtn.addEventListener(MouseEvent.CLICK, pressOperator);
    }
    //EVENT TO ADD OPERATORS TO DISPLAY;
    
    operators[0].y += 383;
    operators[0].x += 198;
    operators[0].caption_op.text = String("/");
    
    operators[1].y += 323;
    operators[1].x += 198;
    operators[1].caption_op.text = String("*");
    
    operators[2].y += 263;
    operators[2].x += 198;
    operators[2].caption_op.text = String("-");
    
    operators[3].y += 203;
    operators[3].x += 198;
    operators[3].caption_op.text = String("+");
    
    /*operators[4].y += 263;
    operators[4].x += 256;
    operators[4].caption_op.text = String("-/+");*/
    
    
    
    //ADD DOT
    var dot:Btn_dot = new Btn_dot();
    	dot.width = 48;
    	dot.height = 48;
    	dot.buttonMode = true;
    	dot.mouseChildren = false;
    	dot.caption_op.text = String (".");
    	addChild(dot);
    
    dot.y += 383;
    dot.x += 78;
    dot.addEventListener(MouseEvent.CLICK, addDot);//EVENT TO ADD DOT TO DISPLAY
    
    //BACKSPACE
    var goBack:Btn_backspace = new Btn_backspace();
    	goBack.width = 48;
    	goBack.height = 48;
    	goBack.buttonMode = true;
    	goBack.mouseChildren = false;
    	goBack.caption_op.text = String ("<--");
    	addChild(goBack);
    
    goBack.y += 203;
    goBack.x += 256;
    goBack.addEventListener(MouseEvent.CLICK, backSpace);//EVENT TO GO BACK SPACE IN DISPLAY
    
    //clearAll
    var clearAll:Btn_clear = new Btn_clear();
    	clearAll.width = 48;
    	clearAll.height = 48;
    	clearAll.buttonMode = true;
    	clearAll.mouseChildren = false;
    	clearAll.caption_op.text = String ("C");
    	addChild(clearAll);
    
    clearAll.y += 323;
    clearAll.x += 256;
    clearAll.addEventListener(MouseEvent.CLICK, clearFields);//EVENT TO GO BACK SPACE IN DISPLAY
    
    
    
    //EQUALS
    var equals:Btn_equals = new Btn_equals();
    equals.width = 48;
    equals.height = 48;
    equals.buttonMode=true;
    equals.mouseChildren=false;
    equals.caption_op.text=String("=");
    addChild(equals);
    	
    equals.y += 383;
    equals.x += 138;
    equals.addEventListener(MouseEvent.CLICK, performEquals);
    //EVENT TO CALCULATE
    
    
    //VARIABLE HANDLE OPERATION NOT BUTTON
    var operates:String;
    
    //HANDLE FIRST AND SECOND VALUE
    var num1:Number;
    var num2:Number;
    
    var num1S:String="";
    var num2S:String="";
    
    var currentNumber:String="";
    function pressNumber(e:MouseEvent):void {
    	 var opBtn1:Btn_operator = new Btn_operator();
    	opBtn1.buttonMode = false;
        display_txt.appendText(e.currentTarget.num);
        if (operatorSelected) {
            num2S+=e.currentTarget.num;
            num2=Number(num2S);
        } else {
            num1S+=e.currentTarget.num;
            num1=Number(num1S);
        }
    }
    
    
    //DISPLAY OPERATORS
    function pressOperator(event:MouseEvent):void {
        operatorSelected = true;
        operates=operate[operators.indexOf(event.target)];
        display_txt.appendText(operate[operators.indexOf(event.target)]);
        trace(operate[operators.indexOf(event.target)]);
    }
    
    //CLEARS DISPLAY AREA
    function clearFields(event:MouseEvent):void{
    	display_txt.text = "";
    	answer_txt.text = "";
    	num1=NaN;
    	num2=NaN;
    	}
    
    //ADDS DECIMAL PLACE
    function addDot(event:MouseEvent):void{
    	if(event.currentTarget.num == Number(display_txt.text))
    	{
    	display_txt.text = "0";
    	}
    	if (display_txt.text.indexOf(".")==-1){
    		display_txt.appendText(".");
    
    	}
    	
    	}
    //BACKSPACE DISPLAY AREA
    function backSpace(e:MouseEvent):void{
    	var temp_str:String = display_txt.text;
    	display_txt.text = temp_str.substr(0, (temp_str.length-1)); // Get rid of last character in the string, which in this case is the phantom \r or \n character
    }
    
    var devideZero:Boolean;
    function performCalculation():void {
        operatorSelected = false;
        switch (operates) {
            case "÷" :
                if(num2 != 0) {
        		num1 /= num2;
    			}else{
         		answer_txt.text = "Cannot devide by zero";
         devideZero = true;
    	 }
                break;
            case "x" :
                num1*=num2;
                break;
            case "-" :
                num1-=num2;
                break;
            case "+" :
                num1+=num2;
                break;
            default :
                break;
        }
    }
     
    function performEquals(e:MouseEvent):void {
    	num1S="";
        num2S="";
    	 performCalculation();
    	 answer_txt.text=num1.toPrecision(2);
    	trace(num1.toPrecision(2));//traces
    	if(!devideZero){
        answer_txt.text=String(num1);
    	}
    	num2 = NaN;
    }
    
    

  • MalgarasMalgaras Registered User regular
    edited March 2012
    Your decimal is only getting appended to your display text, not to the actual string you are using to build the number. That is why it doesn't actually get used in the calculation. You set up your strings to hold your numbers while you build them a little differently than I expected, but this still applies.

    To keep people from leading with an operator, simply check if num1 is set (not NaN) when they try to enter an operator. If num1 isn't set, simply don't do anything.

    Malgaras on
    1tLJUH2O.png
  • littlea5hlittlea5h Registered User regular
    I think i am getting confused myself too just by looking at it lol. Thank you.

Sign In or Register to comment.