Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Currently, I\'m getting this as my output: \"Exception in thread \"main\" java.l

ID: 3837408 • Letter: C

Question

Currently, I'm getting this as my output:

"Exception in thread "main" java.lang.NullPointerException
   at InfixExpression.execute(InfixExpression.java:98)
   at InfixExpression.Evaluate(InfixExpression.java:65)
   at InfixExpression.setWholeExpr(InfixExpression.java:24)
   at InfixExpression.<init>(InfixExpression.java:17)
   at Main.testHW1(Main.java:17)
   at Main.main(Main.java:6)"

I need to get this as my output:

"Testing InfixExpression:
When passing null, the String and double = Infix String: , result: 0.0
When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805
..."

I wrote all the code, but I don't know where it went wrong.

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

public class Main {
   public static void main(String[] args){
       testHW1();

   // YOU'RE NOT ALLOWED TO CHANGE THIS METHOD, AND YOU MUST USE IT:
   }
   public static Scanner userScanner = new Scanner(System.in);
  
   // call this method as indicated in HW#1, and don't change the method NOR
   // the size of your ArrayStack:
   public static void testHW1() { // testing InfixExpression more:
       InfixExpression infix1, infix2;
       infix1 = new InfixExpression(null);
       infix2 = new InfixExpression("( 234.5 * ( 5.6 + 7.0 ) ) / 100.2");
       System.out.println(" Testing InfixExpression:");
       System.out.println("When passing null, the String and double = " + infix1.toString());
       System.out.println("When passing a valid String, the String and double = " + infix2.toString());

       // testing ArrayStack and LinkedStack more:
       ArrayStack<String> arrStack = new ArrayStack<>();
       LinkedStack<String> linkStack = new LinkedStack<>();
       String[] strArray = { "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth",
               "Tenth" };

       // Testing ArrayStack
       System.out.println(" Testing the ArrayStack:");
       for (int i = 0; i < strArray.length; ++i) {
           if (!arrStack.push(strArray[i] + " 1"))
               System.out.println("Error: couldn't push " + strArray[i] + " 1");
       }
       for (int i = 0; i < strArray.length; ++i) {
           if (!arrStack.push(strArray[i] + " 2")) {
               System.out.println("Out of space, removing " + arrStack.pop());
               if (!arrStack.push(strArray[i] + " 2"))
                   System.out.println("Error pushing!" + strArray[i] + " 2");
           }
       }
       System.out.println("The size of the ArrayStack is now " + arrStack.size());
       while (!arrStack.isEmpty()) {
           System.out.println("Popping " + arrStack.pop());
       }
       System.out.println("The size of the ArrayStack is now " + arrStack.size());
       if (!arrStack.push(strArray[0] + " 3"))
           System.out.println("Error: couldn't push " + strArray[0] + " 3");
       else
           System.out.println(
                   "After pushing " + arrStack.peek() + ", the size of the ArrayStack is now " + arrStack.size());
       // testing LinkedStack
       System.out.println(" Testing the LinkedStack:");
       for (int i = 0; i < strArray.length; ++i)
           linkStack.push(strArray[i] + " 4");
       System.out.println("The size of the LinkedStack is " + linkStack.size());
       for (int i = 0; i < strArray.length / 2; ++i) {
           System.out.println("Popping " + linkStack.pop());
       }
       System.out.println("The size of the LinkedStack is now " + linkStack.size());
       while (!linkStack.isEmpty()) {
           System.out.println("Popping " + linkStack.pop());
       }
       System.out.println("The size of the LinkedStack is now " + linkStack.size());
       if (!linkStack.push(strArray[0] + " 5"))
           System.out.println("Error: couldn't push " + strArray[0] + " 5");
       else
           System.out.println(
                   "After pushing " + linkStack.peek() + ", the size of the LinkedStack is now " + linkStack.size());

   } // end stackTester
  
   public static Scanner openInputFile() {
       String filename;
       Scanner scanner = null;

       System.out.print("Enter the input filename: ");
       filename = userScanner.nextLine();
       File file = new File(filename);

       try {
           scanner = new Scanner(file);
       } // end try
       catch (FileNotFoundException fe) {
           System.out.println("Can't open input file ");
           return null; // array of 0 elements
       } // end catch
       return scanner;
   } // end openInputFile
}

import java.util.StringTokenizer;
import java.util.ArrayList;

public class InfixExpression {
   private String wholeExpr;
   private ArrayList<String> tokenizedArrayList;
   private double finalResult;

   public InfixExpression() {
       wholeExpr = " ";
       tokenizedArrayList = new ArrayList<String>();
       finalResult = 0;
   }

   public InfixExpression(String expression) {
       this();
       setWholeExpr(expression);
   }

   public void setWholeExpr(String Expr) {
       wholeExpr = Expr;
       if (wholeExpr != null) {
           Tokenize();
           Evaluate();
       }
   }

   public String getWholeExpr() {
       return wholeExpr;
   }

   public double getFinalResult() {
       return finalResult;
   }

   private void Tokenize() {
       String[] tokenizedArray = wholeExpr.split(" ");
       tokenizedArrayList.clear(); // clear the ArrayList
       for (int i = 0; i < tokenizedArray.length; ++i) {
           tokenizedArrayList.add(tokenizedArray[i]); // add the next token to
                                                       // the ArrayList
       }
   }

   private void Evaluate() {
       StackInterface<String> opStack = new ArrayStack<>();
       StackInterface<Double> valStack = new LinkedStack<>();
       for (int i = 0; i < tokenizedArrayList.size(); i++) {
           String token = tokenizedArrayList.get(i);
           if (OpChecker(token)) {
               if (opStack.isEmpty()) {
                   opStack.push(token);
               } else if (Precedence(token) > Precedence(opStack.peek())) {
                   opStack.push(token);
               } else {
                   while (!opStack.isEmpty() && Precedence(token) <= Precedence(opStack.peek())) {
                       execute(opStack, valStack);
                   }
                   opStack.push(token);
               }
           } else if (token.equals("(")) {
               opStack.push(token);
           } else if (token.equals(")")) {
               while (opStack.peek() != "(") {
                   execute(opStack, valStack);
               }
               opStack.pop();
           } else {
               valStack.push(Double.parseDouble(token));
           }
       }

       while (!opStack.isEmpty()) {
           execute(opStack, valStack);
       }
       if (valStack.size() == 1) {
           finalResult = valStack.peek();
       } else {
           finalResult = 0;
       }
   }

   private void execute(StackInterface<String> opStack, StackInterface<Double> valStack) {
       double rightOperand = 0;
       double leftOperand = 0;
       double temp = 0;
       String op = opStack.pop();
       if (valStack.isEmpty()) {

       } else {
           rightOperand = valStack.pop();
       }
       if (valStack.isEmpty()) {

       } else {
           leftOperand = valStack.pop();
       }
       switch (op) {
       case "+":
           temp = leftOperand + rightOperand;

       case "-":
           temp = leftOperand - rightOperand;

       case "*":
           temp = leftOperand * rightOperand;

       case "/":
           temp = leftOperand / rightOperand;

       }
       valStack.push(temp);
   }

   private boolean OpChecker(String operator) {
       if (operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/")) {
           return true;
       } else
           return false;
   }

   private int Precedence(String operator) {
       if (operator.equals("(") || operator.equals(")")) {
           return 1;
       } else if (operator.equals("/") || operator.equals("*")) {
           return 3;
       } else
           return 2;
   }

   public String toString() {
       return wholeExpr + ", " + "result: " + finalResult;
   }
}


import java.util.*;
/**
A class of stacks whose entries are stored in an array.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
UPDATED by C. Lee-Klawender
*/

public class ArrayStack<T> implements StackInterface<T>
{
   private T[] stack; // Array of stack entries
   private int topIndex; // Index of top entry
   private static final int DEFAULT_CAPACITY = 5;
   private static final int MAX_CAPACITY = 100;

   public ArrayStack()
   {
this(DEFAULT_CAPACITY);
    } // end default constructor

   public ArrayStack(int initialCapacity)
   {
if(initialCapacity > MAX_CAPACITY)
initialCapacity = MAX_CAPACITY;
else
if( initialCapacity < DEFAULT_CAPACITY )
initialCapacity = DEFAULT_CAPACITY;

// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
   } // end constructor

   public boolean push(T newEntry)
   {
if( topIndex+1 < stack.length )
{
stack[topIndex + 1] = newEntry;
topIndex++;
return true;
}
return false;
   } // end push

   public T peek()
   {
       if (isEmpty()) // UPDATE FOR HW#1
           return null;
       else
return stack[topIndex];
   } // end peek

   public T pop()
   {
       if (isEmpty()) // UPDATE FOR HW#1
           return null;
       else
       {
           T top = stack[topIndex];
           stack[topIndex] = null;
           topIndex--;
return top;
       } // end if
} // end pop
   public boolean isEmpty(){
       if (stack[0] == null){
           return true;
       }
       else
           return false;
   }
  
   public int size(){
       return 0;
   }
// TWO MORE METHODS ARE REQUIRED HERE (PART OF EXERCISE 2.1)

} // end ArrayStack

/**
* A class of stacks whose entries are stored in a chain of nodes.
*
* @author Frank M. Carrano
* @author Timothy M. Henry
* @version 4.0 UPDATED by C. Lee-Klawender
*/
public class LinkedStack<T> implements StackInterface<T> {
   private Node topNode; // References the first node in the chain
   private int numOfEntries;
   // ADD A PRIVATE INT FOR COUNTER THAT INDICATES HOW MANY NODES ARE IN THE
   // STACK

   public LinkedStack() {
       topNode = null;
       numOfEntries = 0;
   } // end default constructor

   public boolean push(T newEntry) {
       topNode = new Node(newEntry, topNode);
       numOfEntries++;
       // ADD CODE SO THE COUNTER IS CORRECT
       return true;
   } // end push

   public T peek() {
       if (isEmpty())
           return null;
       else
           return topNode.getData();
   } // end peek

   public T pop() {
       T top = peek();
       if (topNode != null) {
           topNode = topNode.getNextNode();
           numOfEntries--;
           // ADD CODE SO THE COUNTER IS CORRECT
       }

       return top;
   } // end pop

   public boolean isEmpty() {
       if (topNode == null) {
           return true;
       } else
           return false;
   } // end isEmpty
   public int size(){
       return numOfEntries;
   }
   // WRITE THE "MISSING" METHOD, REQUIRED FOR THIS CLASS SO IT'S NOT ABSTRACT
   // (also Ex. 2.2):

   private class Node {
       private T data; // Entry in stack
       private Node next; // Link to next node

       private Node(T dataPortion) {
           this(dataPortion, null);
       } // end constructor

       private Node(T dataPortion, Node linkPortion) {
           data = dataPortion;
           next = linkPortion;
       } // end constructor

       private T getData() {
           return data;
       } // end getData

       private void setData(T newData) {
           data = newData;
       } // end setData

       private Node getNextNode() {
           return next;
       } // end getNextNode

       private void setNextNode(Node nextNode) {
           next = nextNode;
       } // end setNextNode
   } // end Node

} // end LinkedStack

public interface StackInterface<T>
{
/** Adds a new entry to the top of this stack.
@param newEntry An object to be added to the stack. */
public boolean push(T newEntry);

/** Removes and returns this stack's top entry.
@return The object at the top of the stack.
or null if the stack is empty*/
public T pop();

/** Retrieves this stack's top entry (without removing).
@return The object at the top of the stack.
or null if the stack is empty. */
public T peek();

/** Detects whether this stack is empty.
@return True if the stack is empty. */
public boolean isEmpty();

/** Returns number of items in this stack
@return: Number of items */
public int size();

} // end StackInterface

PLEASE HALPPP!!!

Explanation / Answer

Made changes only in InfixExpression.java class

PROGRAM CODE:

package stack;

import java.util.StringTokenizer;
import java.util.ArrayList;
public class InfixExpression {
private String wholeExpr;
private ArrayList<String> tokenizedArrayList;
private double finalResult;
public InfixExpression() {
wholeExpr = " ";
tokenizedArrayList = new ArrayList<String>();
finalResult = 0;
}
public InfixExpression(String expression) {
this();
setWholeExpr(expression);
}
public void setWholeExpr(String Expr) {
wholeExpr = Expr;
if (wholeExpr != null) {
Tokenize();
Evaluate();
}
}
public String getWholeExpr() {
return wholeExpr;
}
public double getFinalResult() {
return finalResult;
}
private void Tokenize() {
String[] tokenizedArray = wholeExpr.split(" ");
tokenizedArrayList.clear(); // clear the ArrayList
for (int i = 0; i < tokenizedArray.length; ++i) {
tokenizedArrayList.add(tokenizedArray[i]); // add the next token to
// the ArrayList
}
}
private void Evaluate() {
StackInterface<String> opStack = new ArrayStack<>();
StackInterface<Double> valStack = new LinkedStack<>();
for (int i = 0; i < tokenizedArrayList.size(); i++) {
String token = tokenizedArrayList.get(i);
if (OpChecker(token)) {
if (opStack.isEmpty()) {
opStack.push(token);
} else if (Precedence(token) > Precedence(opStack.peek())) {
opStack.push(token);
} else {
while (!opStack.isEmpty() && Precedence(token) <= Precedence(opStack.peek())) {
execute(opStack, valStack);
}
  
opStack.push(token);
}
} else if (token.equals("(")) {
opStack.push(token);
} else if (token.equals(")")) {
   //added a condition to check if the stack is empty
while (opStack.peek() != "(" && !opStack.isEmpty()) {
execute(opStack, valStack);
}
  
} else {
valStack.push(Double.parseDouble(token));
}
}
while (!opStack.isEmpty()) {
execute(opStack, valStack);
}
if (valStack.size() == 1) {
finalResult = valStack.peek();
} else {
finalResult = 0;
}
}
private void execute(StackInterface<String> opStack, StackInterface<Double> valStack) {
double rightOperand = 0;
double leftOperand = 0;
double temp = 0;
String op = opStack.pop();
if (valStack.isEmpty()) {
   return;
} else {
rightOperand = valStack.pop();
}
if (valStack.isEmpty()) {
   valStack.push(rightOperand);
   return;
} else {
leftOperand = valStack.pop();
}
// System.out.println("OP=" + op + " left=" + leftOperand + " right=" + rightOperand);
//break statements were missing here
switch (op) {
case "+":
temp = leftOperand + rightOperand; break;
case "-":
temp = leftOperand - rightOperand;break;
case "*":
temp = leftOperand * rightOperand;break;
case "/":
temp = leftOperand / rightOperand;break;
//added default to push back the operands in case the op is wrong
default: valStack.push(leftOperand);
            valStack.push(rightOperand);
                return;
}
//System.out.println("After removing op: " + opStack.peek());
//System.out.println(temp);
valStack.push(temp);
}
private boolean OpChecker(String operator) {
if (operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/")) {
return true;
} else
return false;
}
private int Precedence(String operator) {
if (operator.equals("(") || operator.equals(")")) {
return 1;
} else if (operator.equals("/") || operator.equals("*")) {
return 2;
} else
return 3;
}
public String toString() {
return wholeExpr + ", " + "result: " + finalResult;
}

}

OUTPUT:


Testing InfixExpression:
When passing null, the String and double = null, result: 0.0
When passing a valid String, the String and double = ( ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2 ), result: 29.488023952095805

Testing the ArrayStack:
Error: couldn't push Sixth 1
Error: couldn't push Seventh 1
Error: couldn't push Eighth 1
Error: couldn't push Ninth 1
Error: couldn't push Tenth 1
Out of space, removing Fifth 1
Out of space, removing First 2
Out of space, removing Second 2
Out of space, removing Third 2
Out of space, removing Fourth 2
Out of space, removing Fifth 2
Out of space, removing Sixth 2
Out of space, removing Seventh 2
Out of space, removing Eighth 2
Out of space, removing Ninth 2
The size of the ArrayStack is now 0
Popping Tenth 2
Popping Fourth 1
Popping Third 1
Popping Second 1
Popping First 1
The size of the ArrayStack is now 0
After pushing First 3, the size of the ArrayStack is now 0

Testing the LinkedStack:
The size of the LinkedStack is 10
Popping Tenth 4
Popping Ninth 4
Popping Eighth 4
Popping Seventh 4
Popping Sixth 4
The size of the LinkedStack is now 5
Popping Fifth 4
Popping Fourth 4
Popping Third 4
Popping Second 4
Popping First 4
The size of the LinkedStack is now 0
After pushing First 5, the size of the LinkedStack is now 1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote