Need Help...
How can I compute a string data type?
For example, the value of variable strInput is "1+2+3-4*5", and the answer must be -14.
Need reply ASAP! I know its very simple for you.
Printable View
Need Help...
How can I compute a string data type?
For example, the value of variable strInput is "1+2+3-4*5", and the answer must be -14.
Need reply ASAP! I know its very simple for you.
Code:import java.util.* ;
public class MyApp
{
public static void main ( String args[] )
{
Scanner s = new Scanner( System.in ) ;
System.out.println( "Please enter the mathematical expression" ) ;
String expression = s.nextLine() ;
Stack<Character> stNumbers = new Stack() ;
Stack<Character> stOps = new Stack() ;
for ( char c : expression.toCharArray() )
{
if ( Character.isDigit( c ) )
{
stNumbers.push( c ) ;
}
else
{
stOps.push( c ) ;
}
}
double value = Double.parseDouble( stNumbers.pop().toString() ) ;
while ( !stOps.isEmpty() )
{
double op2 = Double.parseDouble( stNumbers.pop().toString() ) ;
switch ( stOps.pop().charValue() )
{
case '+':
value += op2 ;
break ;
case '-':
op2 -= value ;
value = op2 ;
break ;
case '*':
value *= op2 ;
break ;
case '/':
op2 /= value ;
value = op2 ;
break ;
}
}
System.out.println( "The value of the expression is " + value ) ;
}
}
That was a very simple algorithm I rapidly created. It doesn't prioritize division and multiplication over summation and subtraction, you need to work on it a little bit
Yup! Priority is needed.
Guess who's job is thathttp://img.photobucket.com/albums/v6...ion/1ptgno.gifQuote:
Originally Posted by everard
Do your own homeworkQuote:
Originally Posted by everard
Your signature is ironic.Quote:
Originally Posted by everard
Quote:
Originally Posted by penagate
:lol: I almost said something about that in my post.
you would need to use a for loop to run through it to prioritize...
Huh? What's a for-loop got to do with an abstract parsing problem?
I was stating that you would use a for loop to check for the order of operations
outer loop for addition
1 inner subtraction
2 inner for mulitiplication
3 inner for division
4th for exponets
There's a way to do the parathesises but it isn't hitting right now, another for loop that leads to a method to deal with them...
Yeah you are right, and I think it's a third Stack for parenthesisQuote:
Originally Posted by vagabon