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("\nTesting
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("\nTesting 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("\nTesting 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\n");
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!!!
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
Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException at InfixExpression.execute(InfixExpression.java:98) ...
Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...
I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> { // Data fields private Node<T> topNode; // references the first node in the chain private int numberOfEntries; public...
Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods: peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...
Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods: peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...
Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix) { LinkedStack stack2 = new LinkedStack(); int val1; int val2; int result; for(int i = 0; i < postFix.length(); i++) { char m = postFix.charAt(i); if(Character.isDigit(m)) { stack2.push(m); } else { ...
Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...
In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These files will need to be added to your Java project. They provide data structure functionality that you will build over. It is suggested that you test if these files have been properly added to your project by confirming that Base_A05Q1.java compiles correctly. Complete the implementation of the ArrayStack class. Specifically, complete the implementations of the isEmpty, size, and toString methods. See Base_A05Q1.java for a...
Stack help. I need help with my lab assignment. Complete a method for a class named Palindrome that evaluates a string phrase to determine if the phrase is a palindrome or not. A palindrome is a sequence of characters that reads the same both forward and backward. When comparing the phrase to the same phrase with the characters in reverse order, an uppercase character is considered equivalent to the same character in lowercase, and spaces and punctuation are ignored. The...
What is wrong with my code, when I pass in 4 It will not run, without the 4 it will run, but throw and error. I am getting the error required: no arguments found: int reason: actual and formal argument lists differ in length where T is a type-variable: T extends Object declared in class LinkedDropOutStack public class Help { /** * Program entry point for drop-out stack testing. * @param args Argument list. */ public static void main(String[] args)...
*JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> { private int top, size; private E arrS[]; private static final int MAX_STACK_SIZE = 10; public ArrayStack() { this.arrS = (E[]) new Object[MAX_STACK_SIZE]; this.top = size; this.size = 0;...