This is a code converting infix expressions to postfix expression and evaluates it. there is a problem, when i run it in ECLIPSE, it it displays this errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "4+4"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:456)
    at java.lang.Integer.parseInt(Integer.java:497)
    at Postfix.toPostfix(Postfix.java:39)
    at Postfix.main(Postfix.java:21)

Can anybody help me? here's the code:

import java.io.*;
import java.util.*;

public class Postfix
{
private static Stack operators = new Stack();
    private static Stack operands = new Stack();

    public static void main(String argv[]) throws IOException
    {
        String infix;

        //create an input stream object
        BufferedReader keyboard = new BufferedReader (new   
                                                   InputStreamReader(System.in));

        //get input from user
        System.out.print("\nEnter the algebraic expression in infix: ");
        infix = keyboard.readLine();

        //output as postfix
        System.out.println("The expression in postfix is:" + toPostfix(infix));

        //get answer
        System.out.println("The answer to the equation is: " + evaluate
                                                            (toPostfix(infix)) + "\n");
    }

    private static String toPostfix(String infix)
    //converts an infix expression to postfix
    {
        StringTokenizer s = new StringTokenizer(infix);
        //divides the input into tokens
        String symbol, postfix = "";
        while (s.hasMoreTokens())
        //while there is input to be read
        {
            symbol = s.nextToken();
            //if it's a number, add it to the string
            if (Character.isDigit(symbol.charAt(0)))
                postfix = postfix + " " + (Integer.parseInt
                                                                                                         (symbol));
            else if (symbol.equals("("))
            //push (
            {
                Character operator = new Character('(');
                operators.push(operator);
            }
            else if (symbol.equals(")"))
            //push everything back to (
            {
                while (((Character)operators.peek()).charValue() != '(')
                {
                    postfix = postfix + " " + operators.pop();
                }
                operators.pop();
            }
            else
            //print operators occurring before it that have greater precedence
            {
                while (!operators.empty() && !(operators.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operators.peek()).charValue()))
                    postfix = postfix + " " + operators.pop();
                Character operator = new Character(symbol.charAt(0));
                operators.push(operator);
            }
        }
        while (!operators.empty())
            postfix = postfix + " " + operators.pop();
        return postfix;
    }

    private static int evaluate(String postfix)
    {
        StringTokenizer s = new StringTokenizer(postfix);
        //divides the input into tokens
        int value;
        String symbol;
        while (s.hasMoreTokens())
        {
            symbol = s.nextToken();
            if (Character.isDigit(symbol.charAt(0)))
            //if it's a number, push it
            {
                Integer operand = new Integer(Integer.parseInt(symbol));
                operands.push(operand);
            }
            else //if it's an operator, operate on the previous two operands
            {
                int op2 = ((Integer)operands.pop()).intValue();
                int op1 = ((Integer)operands.pop()).intValue();
                int result = 0;
                switch(symbol.charAt(0))
                {
                    case '*': {result = op1 * op2; break;}
                    case '+': {result = op1 + op2; break;}
                    case '-': {result = op1 - op2; break;}
                    case '/': {result = op1 / op2; break;}
                    case '%': {result = op1 % op2; break;}
                }
                Integer operand = new Integer(result);
                operands.push(operand);
            }
        }
        value = ((Integer)operands.pop()).intValue();
        return value;
    }

    private static int prec(char x)
    {
        if (x == '+' || x == '-')
            return 1;
        if (x == '*' || x == '/' || x == '%')
            return 2;
        return 0;
    }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

This is a code converting infix expressions to postfix expression and evaluates it. there is a problem, when i run it in ECLIPSE, it it displays this errors:


Exception in thread "main" java.lang.NumberFormatException: For input string: "4+4"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:456)
at java.lang.Integer.parseInt(Integer.java:497)
at Postfix.toPostfix(Postfix.java:39)
at Postfix.main(Postfix.java:21)

Can anybody help me? here's the code:

import java.io.*;
import java.util.*;

public class Postfix
{
private static Stack operators = new Stack();
private static Stack operands = new Stack();
	
public static void main(String argv[]) throws IOException
{
	String infix;
	
	//create an input stream object
	BufferedReader keyboard = new BufferedReader (new   
                                                 InputStreamReader(System.in));
		
	//get input from user
	System.out.print("\nEnter the algebraic expression in infix: ");
	infix = keyboard.readLine();
		
	//output as postfix
	System.out.println("The expression in postfix is:" + toPostfix(infix));
		
	//get answer
	System.out.println("The answer to the equation is: " + evaluate
                                   (toPostfix(infix)) + "\n");
	}
	
	private static String toPostfix(String infix)
	//converts an infix expression to postfix
	{
		StringTokenizer s = new StringTokenizer(infix);
		//divides the input into tokens
		String symbol, postfix = "";
		while (s.hasMoreTokens())
		//while there is input to be read
		{
			symbol = s.nextToken();
			//if it's a number, add it to the string
			if (Character.isDigit(symbol.charAt(0)))
				postfix = postfix + " " + (Integer.parseInt
                                                                                                         (symbol));
			else if (symbol.equals("("))
			//push (
			{
				Character operator = new Character('(');
				operators.push(operator);
			}
			else if (symbol.equals(")"))
			//push everything back to (
			{
				while (((Character)operators.peek()).charValue() != '(')
				{
					postfix = postfix + " " + operators.pop();
				}
				operators.pop();
			}
			else
			//print operators occurring before it that have greater precedence
			{
				while (!operators.empty() && !(operators.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operators.peek()).charValue()))
					postfix = postfix + " " + operators.pop();
				Character operator = new Character(symbol.charAt(0));
				operators.push(operator);
			}
		}
		while (!operators.empty())
			postfix = postfix + " " + operators.pop();
		return postfix;
	}
	
	private static int evaluate(String postfix)
	{
		StringTokenizer s = new StringTokenizer(postfix);
		//divides the input into tokens
		int value;
		String symbol;
		while (s.hasMoreTokens())
		{
			symbol = s.nextToken();
			if (Character.isDigit(symbol.charAt(0)))
			//if it's a number, push it
			{
				Integer operand = new Integer(Integer.parseInt(symbol));
				operands.push(operand);
			}
			else //if it's an operator, operate on the previous two operands
			{
				int op2 = ((Integer)operands.pop()).intValue();
				int op1 = ((Integer)operands.pop()).intValue();
				int result = 0;
				switch(symbol.charAt(0))
				{
					case '*': {result = op1 * op2; break;}
					case '+': {result = op1 + op2; break;}
					case '-': {result = op1 - op2; break;}
					case '/': {result = op1 / op2; break;}
					case '%': {result = op1 % op2; break;}
				}
				Integer operand = new Integer(result);
				operands.push(operand);
			}
		}
		value = ((Integer)operands.pop()).intValue();
		return value;
	}
	
	private static int prec(char x)
	{
		if (x == '+' || x == '-')
			return 1;
		if (x == '*' || x == '/' || x == '%')
			return 2;
		return 0;
	}
}

You have two threads on the same topic. Please mark one of them solved. Also, please use code tags.

[code=JAVA] // paste code here

[/code]

StringTokenizer st = new StringTokenizer(s);

Creates a StringTokenizer for the String s that uses whitespace (blanks, tabs, newlines, returns, form feeds) as delimiters.

But your input string: "4+4" < doesnt match with any of default delimiters. thats why its showing error.

If still cant get it. Im always here. :)

Regards,
Puneet

Huh? i don't get it.

Use code tags to make your code readable.

http://www.daniweb.com/forums/announcement9-3.html

You don't need to start two threads on the exact same topic. It wastes time because people will respond to one thread, not knowing that someone else responded with the same comments to the other thread. Mark the other one solved and repost your code with code tags so it's readable please.

postfix = postfix + " " + (Integer.parseInt
(symbol));

This line is attempting to change the entire string to a number, not just the number part of the string. The string "4+4" is not a number, even though the charAt(0) is a digit...

StringTokenizer st = new StringTokenizer(s);

Creates a StringTokenizer for the String s that uses whitespace (blanks, tabs, newlines, returns, form feeds) as delimiters.

But your input string: "4+4" < doesnt match with any of default delimiters. thats why its showing error.

If still cant get it. Im always here. :)

Regards,
Puneet

Oh, you mean to add spaces in between?

it has some code smells, although it compiles.. can you help me again..

Stack is a raw type. References to generic type Stack<E> should be parameterized

Type safety: The method push(Object) belongs to the raw type Stack. References to generic type Stack<E> should be parameterized

k kinda figured out that i have to add spaces in between my mathematical expression.. it compiles.. my problem now is that it has some code smells.. i have to clean this job.. can you help me? tnx

Comments
Duplicate threads.

k kinda figured out that i have to add spaces in between my mathematical expression.. it compiles.. my problem now is that it has some code smells.. i have to clean this job.. can you help me? tnx

How can I make this any clearer? You have two threads. One person has already commented on this thread, probably not knowing about the other. People are donating their time here. Be courteous enough not to waste people's time with duplicate threads.

http://www.daniweb.com/forums/thread146370.html

it has some code smells, although it compiles.. can you help me again..

Stack is a raw type. References to generic type Stack<E> should be parameterized

Type safety: The method push(Object) belongs to the raw type Stack. References to generic type Stack<E> should be parameterized

Hello again,

Its working fine with me.

Enter the algebraic expression in infix: 4 + 4 * 2
The expression in postfix is: 4 4 2 * +
The answer to the equation is: 12

Only space is required.

If im still missing something. Please be more clear :)

Regards,
PuneetK

How can I make this any clearer? You have two threads. One person has already commented on this thread, probably not knowing about the other. People are donating their time here. Be courteous enough not to waste people's time with duplicate threads.

http://www.daniweb.com/forums/thread146370.html

Hmmmmm.. sorry if ever waste your time sir! how do i marked my first thread SOLVED?!

Hello again,

Its working fine with me.

Only space is required.

If im still missing something. Please be more clear :)

Regards,
PuneetK

Hello. thank you very much 4 the help you've given. going back to the code, what if i don't want to include spaces in between.. what changes should i make?

Hello. thank you very much 4 the help you've given. going back to the code, what if i don't want to include spaces in between.. what changes should i make?

Ok, Its done!

Enter the algebraic expression in infix: 4+4+3*4/2
The expression in postfix is: 4 4 + 3 4 * 2 / +
The answer to the equation is: 14

import java.io.*;
import java.util.*;

public class Postfix
{
	private static Stack operators = new Stack();
	private static Stack operands = new Stack();

	public static void main(String argv[]) throws IOException
	{
		String infix;

		//create an input stream object
		BufferedReader keyboard = new BufferedReader (new
				InputStreamReader(System.in));

		//get input from user
		System.out.print("\nEnter the algebraic expression in infix: ");
		infix = keyboard.readLine();

		//output as postfix
		System.out.println("The expression in postfix is:" + toPostfix(infix));

		//get answer
		System.out.println("The answer to the equation is: " + evaluate
				(toPostfix(infix)) + "\n");
	}

	private static String toPostfix(String infix)
	//converts an infix expression to postfix
	{
		String symbol, postfix = "";
		
		for (int i = 0; i < infix.length(); i++) {
			symbol = infix.charAt(i)+"";
			//if it's a number, add it to the string
			if (Character.isDigit(symbol.charAt(0)))
				postfix = postfix + " " + (Integer.parseInt
						(symbol));
			else if (symbol.equals("("))
				//push (
			{
				Character operator = new Character('(');
				operators.push(operator);
			}
			else if (symbol.equals(")"))
				//push everything back to (
			{
				while (((Character)operators.peek()).charValue() != '(')
				{
					postfix = postfix + " " + operators.pop();
				}
				operators.pop();
			}
			else
				//print operators occurring before it that have greater precedence
			{
				while (!operators.empty() && !(operators.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operators.peek()).charValue()))
					postfix = postfix + " " + operators.pop();
				Character operator = new Character(symbol.charAt(0));
				operators.push(operator);
			}
		}
		
		while (!operators.empty())
			postfix = postfix + " " + operators.pop();
		return postfix;
	}

	private static int evaluate(String postfix)
	{
		StringTokenizer s = new StringTokenizer(postfix);
		//divides the input into tokens
		int value;
		String symbol;
		while (s.hasMoreTokens())
		{
			symbol = s.nextToken();
			if (Character.isDigit(symbol.charAt(0)))
				//if it's a number, push it
			{
				Integer operand = new Integer(Integer.parseInt(symbol));
				operands.push(operand);
			}
			else //if it's an operator, operate on the previous two operands
			{
				int op2 = ((Integer)operands.pop()).intValue();
				int op1 = ((Integer)operands.pop()).intValue();
				int result = 0;
				switch(symbol.charAt(0))
				{
				case '*': {result = op1 * op2; break;}
				case '+': {result = op1 + op2; break;}
				case '-': {result = op1 - op2; break;}
				case '/': {result = op1 / op2; break;}
				case '%': {result = op1 % op2; break;}
				}
				Integer operand = new Integer(result);
				operands.push(operand);
			}
		}
		value = ((Integer)operands.pop()).intValue();
		return value;
	}

	private static int prec(char x)
	{
		if (x == '+' || x == '-')
			return 1;
		if (x == '*' || x == '/' || x == '%')
			return 2;
		return 0;
	}
}

Used forloop instead of StringTokenizer for toPostfix method.

Regards,
PuneetK

Hmmmmm.. sorry if ever waste your time sir! how do i marked my first thread SOLVED?!

Hmmmmmmm.. Sarcastic, aren't we? At the bottom of your thread, you can click "Mark as Solved". Someone has already merged the two threads though, so it's too late. However, when you feel that THIS thread is solved, you can click "Mark as Solved" on it. It'll be in blue letters at the bottom of the thread, right below the last post.

This question has already been answered. Start a new discussion instead.