This discussion is archived
6 Replies Latest reply: Nov 16, 2006 9:51 AM by 807607 RSS

Java PostFix using input file + exceptions

807607 Newbie
Currently Being Moderated
I'm working on a project that has really stummped me here in the late goings. I need the program to be full proof and not throw exceptions with an input file given + maintain all the right anwsers. The program runs just fine and has the needed methods to generate right anwers, but exception handling is a major problem. Here is the code I hope someone can maybe see what the problem is. Sry about the lenght, it is a long one.

public class ALStack<T> implements Stack
{
private Object stack[];
private int sizeIndex = 100;
private int topPtr;
          
public ALStack()
{
stack = new Object[sizeIndex];
}

public void push(Object stackItem)
{
if(!isFull())
{
     stack[topPtr] = stackItem;
     topPtr++;
}
}

public Object pop()
{
     Object x = null;
     if(!isEmpty())
{
x = stack[--topPtr];
stack[topPtr] = null;
}
return x;
}

public Object top()
{     
     Object ts = null;
if(!isEmpty())
{
     ts = stack[topPtr - 1];
}
return ts;
}

public boolean isEmpty()
{
return topPtr == 0;
}

public boolean isFull()
{
          return topPtr == sizeIndex;          
}

public void clear()
{
     for(int i =0; i < sizeIndex; i++)
{
stack[i] = null;
               topPtr--;
}
}

     public boolean contains(Object stackItem)
     {
          boolean contains = false;
          if(!isEmpty())
          {
               for(int i = 0; i < sizeIndex; i++)
               {
               if(stack.equals(stackItem))
               {
                    contains = true;
                    break;
               }
               }
          }
          return contains;
     }
          
public String toString()
{
StringBuffer display = new StringBuffer();

display.append("{");
for(int i = 0; i< sizeIndex; i++)
{
if(stack[i] != null)
{
display.append(stack[i]);
if( i < topPtr - 1)
{
display.append(",");
}
}
}

display.append("}");
return display.toString();
}

}

public class Numeral
{
     public static boolean isOperand(String o)
     {     
          boolean operand = true;
               for(int i = 0; i < o.length(); i++)
               {
                    char c = o.charAt(i);
                    if(!Character.isDigit(c))
                    {
                         operand = false;
                         break;
                    }     
               }
          return operand;
     }
     
     public static boolean isOperator(String o)
     {
          return(o.equals("+") || o.equals("*") ||
          o.equals("-") || o.equals("/")) || o.equals("^");
     }
}
Here is the work horse and where excpetions need to take place. With the input file sent at the bottom, the third line screws up with a null reference pointer. It needs to just say in the output file that an operand is missing, nothing more.

public interface Stack
{
     public void push(Object item);
     public Object pop();
     public Object top();
     public boolean isEmpty();
     public boolean isFull();
     public void clear();
}

import java.util.*;
import java.io.*;
import java.util.Scanner;
import java.text.DecimalFormat;


public class PostFix
{

     private static double val1,val2;
     private static double result;
     
     public static void main(String[] args) throws IOException
     {
          String filename;
          String inputLine;
          String temp;
          double ans;
          
          ALStack<String> stack = new ALStack<String>();
          
          Scanner keyboard = new Scanner(System.in);
          
          System.out.print("Enter the input filename: ");
          filename = keyboard.nextLine();
          try
          {
               FileReader freader = new FileReader(filename);
               BufferedReader inputFile = new BufferedReader(freader);
          

          
          System.out.print("Enter the output filename: ");
          filename = keyboard.nextLine();
          
          FileWriter fwriter = new FileWriter(filename);
          PrintWriter outputFile = new PrintWriter(fwriter);
          
          outputFile.println("CSC-241-01-Ahlborn processed by Ricky Stierly ");
          inputLine = inputFile.readLine();
          
          while (inputLine != null)
          {
               DecimalFormat fmt1 = new DecimalFormat("#.000");
               StringTokenizer st = new StringTokenizer(inputLine, " ");
               
               while(st.hasMoreElements())
               {     
                    String token = st.nextToken();
                    outputFile.print(token + " ");
                    if(Numeral.isOperand(token))
                    {
                         stack.push(token);
                    }
                    else if(Numeral.isOperator(token))
                    {
                         {
                              val1 = Double.parseDouble(stack.pop().toString());
                              val2 = Double.parseDouble(stack.pop().toString());
                         }
                         if(token.equals("^"))
                         {
                    result = Math.pow(val2, val1);
                    stack.push(new Double(result));
                         }
                         
                         
                         if(token.equals("+"))
                         {
                              result = val1 + val2;
                              stack.push(new Double(result));
                         }
                         else if(token.equals("-"))
                         {
                              result = val2 - val1;
                              stack.push(new Double(result));
                         }
                         else if(token.equals("*"))
                         {
                              result = val1 * val2;
                              stack.push(new Double(result));
                         }
                         else if(token.equals("/"))
                         {
                              result = val2 / val1;
                              stack.push(new Double(result));
                         }
                    }
               }
               
               ans = Double.parseDouble(stack.pop().toString());
               temp = fmt1.format(ans);
               outputFile.println(" = " + temp);
               inputLine = inputFile.readLine();
               
          }
                    
               inputFile.close();
               outputFile.close();
          }
          
          
     
          catch(IOException e)
          {
               System.out.println("I/O Error: File not found");
          }
     }
          
          
}
  • 1. Re: Java PostFix using input file + exceptions
    807607 Newbie
    Currently Being Moderated
    here is the input file I supposed to use:

    its called PostFix1.txt

    3 2 ^ 5 4 - ^ 8 +
    9 8 7 6 5 4 3 / * - + / *
    8 9 2 - # 3 5 - 7 + *
    8.6 -3.4 + * -5.5 19.3 * // first line to throw exception
    4.29 +5.26 * -8.3 - 7 -16 / +
    7 4 -5 * 20 + /
    2.8 -3.5 * 3 / 14.3 -
    4.3 -7.2 6.5 -8.4 + - -3.6 / *
    1.1 2.2 3.3 + - 4.4 5.5 + 6.6 -
    2.8 -7.5 * 6.8 2.4 - /
  • 2. Re: Java PostFix using input file + exceptions
    807607 Newbie
    Currently Being Moderated
    Try posting the code again, this time using the code tags, just highlight the code, and click on the code button just above the edit field.

    and describe exactly what your problem is, not just "Exeception Handling is a major problem"
  • 3. Re: Java PostFix using input file + exceptions
    807607 Newbie
    Currently Being Moderated
    The problem is that the program throws exceptions when the stack is empty after a pop has been made for the else if(Numeral.isOperator(token)). Which is the 4 line from the input file. What needs to happen for that case is the exception to be handled and just output a message to the outputfile that the expressed didn't have enough operators. The check I'm guessing must be done each time I go to pop the next two operators off the stack.                     else if(Numeral.isOperator(token))
                        {
                             {
                                  val1 = Double.parseDouble(stack.pop().toString());
                                  val2 = Double.parseDouble(stack.pop().toString());
                             }

    since at any point the stack can be empty. There is other problems with error checking as well, division by 0, illegal operand, and too many operands, but this one is the most important.

    Thanks in advance
  • 4. Re: Java PostFix using input file + exceptions
    807607 Newbie
    Currently Being Moderated
    here is the code better formatted
    import java.util.*;
    import java.io.*;
    import java.util.Scanner;
    import java.text.DecimalFormat;
    
    
    public class PostFix
    {
    
         private static double val1,val2;
         private static double result;
         
         public static void main(String[] args) throws IOException
         {
              String filename;
              String inputLine;
              String temp;
              double ans;
              
              ALStack<String> stack = new ALStack<String>();
              
              Scanner keyboard = new Scanner(System.in);
              
              System.out.print("Enter the input filename: ");
              filename = keyboard.nextLine();
              try
              {
                   FileReader freader = new FileReader(filename);
                   BufferedReader inputFile = new BufferedReader(freader);
              
    
              
              System.out.print("Enter the output filename: ");
              filename = keyboard.nextLine();
              
              FileWriter fwriter = new FileWriter(filename);
              PrintWriter outputFile = new PrintWriter(fwriter);
              
              outputFile.println("CSC-241-01-Ahlborn processed by Ricky Stierly ");
              inputLine = inputFile.readLine();
              
              while (inputLine != null)
              {
                   DecimalFormat fmt1 = new DecimalFormat("#.000");
                   StringTokenizer st = new StringTokenizer(inputLine, " ");
                   
                   while(st.hasMoreElements())
                   {     
                        String token = st.nextToken();
                        outputFile.print(token + " ");
                        if(Numeral.isOperand(token))
                        {
                             stack.push(token);
                        }
                        else if(Numeral.isOperator(token))
                        {
                             {
                                  val1 = Double.parseDouble(stack.pop().toString());
                                  val2 = Double.parseDouble(stack.pop().toString());
                             }
                             if(token.equals("^"))
                             {
                               result = Math.pow(val2, val1);
                               stack.push(new Double(result));
                             }
                             
                             
                             if(token.equals("+"))
                             {
                                  result = val1 + val2;
                                  stack.push(new Double(result));
                             }
                             else if(token.equals("-"))
                             {
                                  result = val2 - val1;
                                  stack.push(new Double(result));
                             }
                             else if(token.equals("*"))
                             {
                                  result = val1 * val2;
                                  stack.push(new Double(result));
                             }
                             else if(token.equals("/"))
                             {
                                  result = val2 / val1;
                                  stack.push(new Double(result));
                             }
                        }
                   }
                   
                   ans = Double.parseDouble(stack.pop().toString());
                   temp = fmt1.format(ans);
                   outputFile.println(" = " + temp);
                   inputLine = inputFile.readLine();
                   
              }
                        
                   inputFile.close();
                   outputFile.close();
              }
              
              
         
              catch(IOException e)
              {
                   System.out.println("I/O Error: File not found");
              }
         }
              
              
    }
    public class Numeral
    {
         public static boolean isOperand(String o)
         {     
              boolean operand = true;
                   for(int i = 0; i < o.length(); i++)
                   {
                        char c = o.charAt(i);
                        if(!Character.isDigit(c))
                        {
                             operand = false;
                             break;
                        }     
                   }
              return operand;
         }
         
         public static boolean isOperator(String o)
         {
              return(o.equals("+") || o.equals("*") || 
                     o.equals("-") || o.equals("/")) || o.equals("^");
         }
    }
    public class ALStack<T> implements Stack
    {
        private Object stack[];
        private int sizeIndex = 100;
        private int topPtr;
              
        public ALStack()
        {
            stack = new Object[sizeIndex];
        }
        
        public void push(Object stackItem)
        { 
            if(!isFull())
            {
                 stack[topPtr] = stackItem;
                 topPtr++;
            }     
        }
        
        public Object pop()
        {
             Object x = null;
             if(!isEmpty())
            {
                x = stack[--topPtr];
                stack[topPtr] = null;
            }
            return x;
        }
        
        public Object top()
        {     
             Object ts = null;
            if(!isEmpty())
            {
                 ts = stack[topPtr - 1];
            }
            return ts;  
        }
        
        public boolean isEmpty()
        {
            return topPtr == 0;
        }
        
        public boolean isFull()
        {
              return topPtr == sizeIndex;           
        }
        
        public void clear()
        {
              for(int i =0; i < sizeIndex; i++)
            {
                stack[i] = null;
                   topPtr--;
            }
        }
            
         public boolean contains(Object stackItem)
         {
               boolean contains = false;
               if(!isEmpty())
               {
                    for(int i = 0; i < sizeIndex; i++)
                   {
                    if(stack.equals(stackItem))
                   {
                        contains = true;
                        break;
                   }
                   }
              }
              return contains;
         }
              
    public String toString()
    {
    StringBuffer display = new StringBuffer();

    display.append("{");
    for(int i = 0; i< sizeIndex; i++)
    {
    if(stack[i] != null)
    {
    display.append(stack[i]);
    if( i < topPtr - 1)
    {
    display.append(",");
    }
    }
    }

    display.append("}");
    return display.toString();
    }

    }

    public interface Stack
    {
         public void push(Object item);
           public Object pop();
           public Object top();
           public boolean isEmpty();
           public boolean isFull();
           public void clear();  
    }
  • 5. Re: Java PostFix using input file + exceptions
    807607 Newbie
    Currently Being Moderated
    else if(Numeral.isOperator(token))
                {
                     
                     if(!stack.isEmpty())
                     {
                          val1 = Double.parseDouble(stack.pop().toString());
                     }
                     else
                     {
                          System.out.println("Not Enough operands.");
                          break;
                     }
                     
                     if(!stack.isEmpty())                              
                     {
                          val2 = Double.parseDouble(stack.pop().toString());
                     }
                     else
                     {
                          System.out.println("Not enough operands.");
                          break;
                     }
                }
    Just check the stack before you pop, if it's empty, you know there's not enough operands to complete the equation.

    SE*
  • 6. Re: Java PostFix using input file + exceptions
    807607 Newbie
    Currently Being Moderated
    thanks for the help, I thought for some reason I coudn't just use an IF Else statement, that I needed to throw an NullPointerException, then catch it later. However you win the prize. I think I can now build the rest I need, well at least I hope. I'm pretty sure i can make division by zero, illegal operand, too many operands error checking as well. If not look for a post.

    Again thanks !!!!