Results 1 to 8 of 8
  1. #1
    CountBale is offline Member
    Join Date
    Jan 2014
    Posts
    3
    Rep Power
    0

    Default Help with my calculator?

    For a piece of coursework I have to write a calculator in java, I've written the code but no matter what input I enter it throws:

    Exception in thread "main" java.util.EmptyStackException
    at java.util.Stack.peek(Unknown Source)
    at javaCoursework.Calculator.doCalculations(Calculato r.java:196)
    at javaCoursework.Calculator.calculate(Calculator.jav a:208)
    at javaCoursework.CalcMain.main(CalcMain.java:31)

    as an error, can anyone help me figure out what is causing this? I dont really know much about debugging

    The code is here:

    Main:

    Java Code:
    package javaCoursework;
    
    import java.util.Scanner;
    
    public class CalcMain 
    {
    	
    		public static void main(String[] args)
    		{
    			//Creates a new scanner
    			Scanner scanner = new Scanner (System.in);
    			
    			Calculator calculator = new Calculator();
    			
    			Boolean running = true;
    			
    			float result = 0;
    			
    			while(running == true)
    			{
    				//Get the user input
    				System.out.println("Please enter your expression with single spaces separating the terms or enter 'exit' to close: ");
    				String inputString = scanner.nextLine();
    				
    				if(inputString == "exit")
    				{
    					running = false;
    				}
    				else
    				{
    					result = calculator.calculate(inputString);
    					System.out.printf(inputString," = ", result);
    				}
    			}
    			
    			
    			
    			
    			
    			
    			
    			
    			scanner.close();
    		}
    }
    The calculator class:

    Java Code:
    package javaCoursework;
    
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;
    import java.util.Stack;
    
    public class Calculator 
    {
    	//Variables
    	Queue<String> processQueue = new LinkedList<String>();
    	Queue<String> outputQueue = new LinkedList<String>();
    	
    	
    	//Constructor
    	public Calculator()
    	{
    		
    	}
    	
    	//Private Methods
    	//The method to get the priority of an operator
    	private int getPriority(String operator)
    	{
    		switch(operator)
    		{
    			case"+":
    			case"-":
    				return 2;
    			case"*":
    			case"/":
    				return 3;
    			case"^":
    				return 4;
    		}
    		return 0;
    	}
    	
    	//The method to raise a float to an integer power
    	private float power(float base, int exponent)
    	{
    		float result = base;
    		for(int x = 1; x < exponent; x++)
    		{
    			result = result*base;
    		}
    		
    		return result;
    	}
    	
    	//The method to parse the input into a queue to be processed
    	public boolean parseInput(String input)
    	{
    		//Creates a scanner
    		Scanner scanner = new Scanner (input);
    		//A temporary variable
    		String tempChar;
    		//While there is something left in the string
    		while(scanner.hasNext())
    		{
    			//If it's a float
    			if(scanner.hasNextFloat())
    			{
    				//Add it to the queue
    				processQueue.add(Float.toString(scanner.nextFloat()));
    			}
    			//If it's a - it could be a subtraction or a negative number
    			else if(scanner.hasNext("-"))
    			{
    				
    				tempChar = scanner.next();
    				//If there is a space after it, it's a subtractions
    				if(scanner.hasNext(" "))
    				{
    					processQueue.add(tempChar);
    				}
    				//If there is a number after it, it's a negative number
    				else if(scanner.hasNextFloat())
    				{
    					processQueue.add(Float.toString(scanner.nextFloat() * -1));
    				}
    			}
    			//If there's not a space, add the next item to the queue
    			else if(!scanner.hasNext(" "))
    			{
    				processQueue.add(scanner.next());
    			}
    		}
    		//Close the scanner and end the function
    		scanner.close();
    		return true;
    	}
    
    	//The function to put the expression into reverse polish
    	public boolean shuntingYard()
    	{
    		//The operator stack
    		Stack<String> operatorStack = new Stack<String>();
    		String operators = "+-*/^";
    		
    		int y = 0;
    		int expLen = processQueue.size();
    		
    		//go through the whole queue
    		for(int x = 0; x < expLen; x++)
    		{
    			//If it's an operand, add it to the stack
    			if(processQueue.peek().matches("[0-9]+"))
    			{
    				System.out.println("Operand");
    				outputQueue.add(processQueue.poll());
    			}
    			//If it's an operator
    			else if(operators.contains(processQueue.peek()))
    			{
    				//If there's something on the stack
    				if(!operatorStack.empty())
    				{
    					//If the operator has a lower priority or the same priority and is left associative
    					if((getPriority(processQueue.peek())<getPriority(operatorStack.peek()))||((getPriority(processQueue.peek())==getPriority(operatorStack.peek())&&(processQueue.peek() != "^"))))
    					{
    						//Pop the top of the stack onto the output queue
    						outputQueue.add(operatorStack.pop());
    					}
    				}
    				//Add the current operator to the stack
    				operatorStack.push(processQueue.poll());
    			}
    			//If it's a left parenthesis
    			else if(processQueue.peek() == "(")
    			{
    				//Add it to the stack
    				operatorStack.push(processQueue.poll());
    			}
    			//If it's a right parenthesis
    			else if(processQueue.peek() == ")")
    			{
    				//Pop items off the stack onto the queue until you hit a left parenthesis
    				while(y != 1)
    				{
    					if(operatorStack.peek() == "(")
    					{
    						operatorStack.pop();
    						y = 1;
    					}
    					else if(!operatorStack.empty())
    					{
    						outputQueue.add(operatorStack.pop());
    					}
    					//If there isn't a left parenthesis, then the parenthesis are mismatched
    					else
    					{
    						System.out.println("Error: Mismatched Parenthesis");
    						return false;
    					}
    				}
    			}
    			else
    			{
    				while(!operatorStack.empty())
    				{
    					if(operatorStack.peek() == "(")
    					{
    						System.out.println("Error: Mismatched Parenthesis");
    						return false;
    					}
    					else
    					{
    						outputQueue.add(operatorStack.pop());
    					}
    				}
    			}
    		}
    		
    		return true;
    	}
    	
    	public float doCalculations()
    	{
    		float result = 0;
    		int tempVal = 0;
    		
    		Stack<Object> outputStack = new Stack<Object>();
    		for(int i = 0; i < outputQueue.size(); i++)
    		{
    			System.out.println(outputQueue.poll());
    		}
    
    		while(outputQueue.peek() != null)
    		{
    			if(outputQueue.peek().equals("+"))
    			{
    				//Do addition
    				outputStack.push((Float) outputStack.pop() + (Float) outputStack.pop());
    				outputQueue.remove();
    			}
    			else if(outputQueue.peek().equals("-"))
    			{
    				//Do subtraction
    				//This is done the same way as addition except the first number is multiplied by negative 1
    				outputStack.push(((Float) outputStack.pop() * -1) + (Float) outputStack.pop());
    				outputQueue.remove();
    			}
    			else if (outputQueue.peek().equals("*"))
    			{
    				//Do multiplication
    				outputStack.push((Float) outputStack.pop() * (Float) outputStack.pop());
    				outputQueue.remove();
    			}
    			else if (outputQueue.peek().equals("/"))
    			{
    				//Do division
    				//The same as multiplication but the first number is changed to 1/x
    				outputStack.push((1.0/(float)(Integer) outputStack.pop()) * (float)(Integer) outputStack.pop());
    				outputQueue.remove();
    			}
    			else if(outputQueue.peek().equals("^"))
    			{
    				tempVal = (Integer) outputStack.pop();
    				outputStack.push(power((float)outputStack.pop(), tempVal));
    				outputQueue.remove();
    			}
    			else
    			{
    				//It must be an operand so it goes on the stack
    				outputStack.push(Integer.parseInt(outputQueue.poll()));
    			}
    		}
    		System.out.print(outputStack.peek());
    		result = (float) outputStack.pop();
    		return result;
    	}
    	
    	public float calculate(String input)
    	{
    		float result = 0;
    		if(parseInput(input))
    		{
    			if(shuntingYard())
    			{
    				result = doCalculations();
    				return result;
    			}
    		}
    		System.out.println("An Error Occurred");
    		return 0;
    	}
    	
    }
    Last edited by CountBale; 01-07-2014 at 08:13 PM.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,874
    Rep Power
    8

    Default Re: Help with my calculator?

    If you don't know much about debugging, now is the perfect time to start learning. Are you using an IDE? If so, most of them come with a great debugger. Even if you aren't using a debugger, tracing through the code with a piece of paper and a pencil will take you a long way. Welcome to programming.

    If you still can't figure it out, I suggest condensing your problem down to an SSCCE instead of posting your whole project. What exact line is throwing the error? What are the values of every variable on that line? What does your stack contain at that line?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    CountBale is offline Member
    Join Date
    Jan 2014
    Posts
    3
    Rep Power
    0

    Default Re: Help with my calculator?

    I think I know what the issue might be, when I am doing the shunting yard algorithm, I check to see if the value is a number but It wont work for floats. How can I check to see if a string is resolvable to a float?

  4. #4
    zFollette is offline ▼ dafuq did I do?
    Join Date
    Dec 2013
    Posts
    203
    Rep Power
    0

    Default Re: Help with my calculator?

    Quote Originally Posted by CountBale View Post
    I think I know what the issue might be, when I am doing the shunting yard algorithm, I check to see if the value is a number but It wont work for floats. How can I check to see if a string is resolvable to a float?
    You could put Float.valueOf(String) in a try catch, if it throws the error, print something like "Invalid Input".

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,353
    Blog Entries
    7
    Rep Power
    20

    Default Re: Help with my calculator?

    The only debugger I like is System.out.println( ... ) with the appropriate argument; sprinkle in some of those statements and see what your algorithm is doing ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    zFollette is offline ▼ dafuq did I do?
    Join Date
    Dec 2013
    Posts
    203
    Rep Power
    0

    Default Re: Help with my calculator?

    Quote Originally Posted by JosAH View Post
    The only debugger I like is System.out.println( ... ) with the appropriate argument; sprinkle in some of those statements and see what your algorithm is doing ...

    kind regards,

    Jos
    Very well put. Sometimes (in the beginning days) that sprinkle down pours onto your program.

  7. #7
    CountBale is offline Member
    Join Date
    Jan 2014
    Posts
    3
    Rep Power
    0

    Default Re: Help with my calculator?

    Ok, I have a new issue now. In the shunting yard algorithm, when it should add an operator to the queue, it pops the operator off the stack but it is never added to the queue.

    The shunting yard algorithm is here:
    Java Code:
    public boolean shuntingYard()
    	{
    		//The operator stack
    		Stack<String> operatorStack = new Stack<String>();
    		String operators = "+-*/^";
    		
    		int y = 0;
    		int expLen = processQueue.size();
    		
    		//go through the whole queue
    		for(int x = 0; x < expLen; x++)
    		{
    			//If it's an operand, add it to the stack
    			try 
    			{
    				Float.valueOf(processQueue.peek());
    				outputQueue.add(processQueue.poll());
    			}
    			//If it's an operator
    			catch (Exception e)
    			{
    				if(operators.contains(processQueue.peek()))
    				{
    					//If there's something on the stack
    					if(!operatorStack.empty())
    					{
    						//If the operator has a lower priority or the same priority and is left associative
    						if((getPriority(processQueue.peek())<getPriority(operatorStack.peek()))||((getPriority(processQueue.peek())==getPriority(operatorStack.peek())&&(processQueue.peek() != "^"))))
    						{
    							//Pop the top of the stack onto the output queue
    							outputQueue.add(operatorStack.pop());
    						}
    					}
    					//Add the current operator to the stack
    					operatorStack.push(processQueue.poll());
    				}
    				//If it's a left parenthesis
    				else if(processQueue.peek() == "(")
    				{
    					//Add it to the stack
    					operatorStack.push(processQueue.poll());
    				}
    				//If it's a right parenthesis
    				else if(processQueue.peek() == ")")
    				{
    					//Pop items off the stack onto the queue until you hit a left parenthesis
    					while(y != 1)
    					{
    						if(operatorStack.peek() == "(")
    						{
    							operatorStack.pop();
    							y = 1;
    						}
    						else if(!operatorStack.empty())
    						{
    							outputQueue.add(operatorStack.pop());
    						}
    						//If there isn't a left parenthesis, then the parenthesis are mismatched
    						else
    						{
    							System.out.println("Error: Mismatched Parenthesis");
    							return false;
    						}
    					}
    				}
    				else
    				{
    					while(!operatorStack.empty())
    					{
    						if(operatorStack.peek() == "(")
    						{
    							System.out.println("Error: Mismatched Parenthesis");
    							return false;
    						}
    						else
    						{
    							outputQueue.add(operatorStack.pop());
    						}
    					}
    				}
    				
    			}
    			
    		}
    		
    		return true;
    	}
    and the delcaration of the queue is:

    Java Code:
    //Variables
    	Queue<String> processQueue = new LinkedList<String>();
    	Queue<String> outputQueue = new LinkedList<String>();

  8. #8
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,703
    Rep Power
    5

    Default Re: Help with my calculator?

    So try the suggestions you've been getting in stead of entirely ignoring them.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. need some help with my calculator
    By Tooks1 in forum New To Java
    Replies: 0
    Last Post: 02-13-2013, 06:38 PM
  2. calculator
    By rithish in forum AWT / Swing
    Replies: 10
    Last Post: 04-25-2011, 11:24 PM
  3. Help with AWT CALCULATOR
    By Megan Dosnueve in forum AWT / Swing
    Replies: 2
    Last Post: 04-04-2011, 05:49 PM
  4. Help in a calculator
    By Ayannie in forum New To Java
    Replies: 6
    Last Post: 01-04-2011, 08:21 PM
  5. Calculator
    By water in forum AWT / Swing
    Replies: 4
    Last Post: 09-23-2009, 06:00 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •