This site requires JavaScript, please enable it in your browser!
Greenfoot back
Mux
Mux wrote ...

2012/12/15

converte a string into a statement

Mux Mux

2012/12/15

#
I want to be able to convert a given string like : "x+2*y==3" into a real code so that i can put this into an if-loop and get a true or false for given x and y. like: x y boolean 1 2 true 6 -3 true ...
Gevater_Tod4711 Gevater_Tod4711

2012/12/15

#
that will realy be not easy. to exchange x and y you just have to use the replace method in the String API but then you have to teach your computer how to count. You have to exchange things like 2*y and put in the value of this calculation. Then you have to do the same for every + or -. If there are just one number at the left and one number at the right of the == operator you have to get the left and the right numberstring convert them into int and check if they're equal. You always have to use the replace method to change the string. But this will realy be hard to program.
Mux Mux

2012/12/15

#
ok. I thought so, but this is realy hard. thanks for the answer.
Mux Mux

2012/12/15

#
Is it possible to quit a method if something happend without stopping greenfoot. Like: int n = 1; if("e" == givenString){ n=1} else if( "c" == given String){n=2} ... if( 1+n == 2) { quitMethod()} ..-other stuff-... is something like the quitMethod() possible? even if the example make no sense at all.
Gevater_Tod4711 Gevater_Tod4711

2012/12/15

#
use return; then the method will abort
danpost danpost

2012/12/15

#
Replace 'quitMethod()' with 'return;'
if(1+n==2) return;
The 'return' statement causes an immediate exit out of the method. If the method is not of 'void' type, a proper type object must be included. For instance, one could have the following method of return type 'boolean' (instead of 'void'):
public boolean timerExpired()
{
    if(timer>0) timer--;
    if(timer==0)
    {
        return true; // returning a boolean value
    }
    return false;
}
The last statement is not executed if the timer was zero because the 'return' statement in the conditional 'if' block will cause an immediate exit from the method. We could have used an 'else' block for the second 'return' statement, but it is not neccessary (and my point would not have been shown so easily). Also, I am not sure if a compiler error would occur using the 'else' block because it may think that an exit could occur without returning a boolean; and it must be sure that a boolean is returned.
danpost danpost

2012/12/15

#
There was also this discussion on mathematical formulas.
Mux Mux

2012/12/15

#
thanks thats what i've expected.
You need to login to post a reply.