java.lang ClassCastException error - java

I am tasked with creating a postFixEvaluator in java and everytime i try to pop an operand using the evaluateTwoOperations method, my program ends and produces the below error. What is causing this? to my knowledge, I have everything typecasted to be a Complex and not a Integer.
"Couldn't run PostfixEvaluator! java.lang.ClassCastException: java.lang.Integer cannot be cast to Complex"
Start of my postFixEvaluator class
#author Cody
*/
import java.util.*;
import java.io.*;
import java.util.StringTokenizer;
public class PostfixEvaluator
{
private static final int STACK_SIZE = 100;
private Stack operand;
private String expression;
private ArrayList<Complex> answers;
public static Complex result;
public void run() throws IOException
{
ArrayList<Complex> a = new ArrayList<>();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader stdin = new BufferedReader(new FileReader("Prog3_1.in"));
operand = new Stack(STACK_SIZE);
boolean eof = false;
while (!eof) //while not done
{
expression = stdin.readLine(); //read a line of expression
//operand.clear(); //clear the stack
if (expression == null) //if no input, end program
{
eof = true;
}
else
{
result = evaluate(expression); //evaluate expression
}
if (result != null) //if the answer is valid
{
System.out.println("\nvalue: " + result.toString());
answers.add(result);//add answer to arrayList
}
else
{
System.out.println("\nInvalid Expression");
}
}
//read the ArrayList and print the results
/*
if (real)
/
for (int i = 0; i < answers.size(); i++)
{
System.out.println(answers.get(i));
}
*/
System.out.println("Normal termination of"
+ "program 3");
}
public Complex evaluate(String expression)
{
boolean valid = true;
StringTokenizer st = new StringTokenizer(expression); //tokenize the expression
String token; //get individual results of readLine
while (valid && st.hasMoreTokens()) //while valid and their are tokens remaining
{
token = st.nextToken(); //get next token
System.out.println("token is: " + token);
if (isOperator(token)) //if token is operator
{
if (isConjugate(token))
{// if token is conjugate
Complex result1 = evaluateConjugate(token);
operand.push(result1);
}
else //evaluate the operator and push the result
{
Complex result1 = evaluateTwoOperations(token);
operand.push(result1);
}
}
else
{
int value = Integer.parseInt(token);
operand.push(value);
}
}
Complex answer = (Complex) operand.pop();
return answer;
}
private Complex evaluateTwoOperations(String op)
{
Complex resultant = null;
if ( operand.isEmpty() )
System.out.println("Invalid Expression!");
else
{
Complex op2 = (Complex) operand.pop();
Complex op1 = (Complex) operand.pop();
switch (op.charAt(0)) //if op == '+'...
{
case '+':
resultant = op1.plus(op2);
break;
case '-':
resultant = op1.minus(op2);
case '*':
resultant = op1.times(op2);
}
return resultant;
}
return null;
}
private boolean isOperator(String token)
{
return token.equals("+") || token.equals("-")
|| token.equals("*") || token.equals("~");
}
private boolean isConjugate(String token)
{
return token.equals("~");
}
private Complex evaluateConjugate(String op)
{
Complex resultant = null;
if (operand.isEmpty())
System.out.println("Invalid Expression!");
else
{
Complex op1 = (Complex) operand.pop();
switch (op.charAt(0)) //if op == '~'
{
case '~':
resultant = op1.conjugate();
}
return resultant;
}
return null;
}
/*
private void outputExpression(String expression)
{
for (int i = 1; i < answers.size(); i++)
{
System.out.println("Expression " + i + ": " + expression);
}
}
*/
}
Start of my Complex class
#author Cody
*/
public class Complex
{
private int realNumber;
private int imagNumber;
private final int checker = 0;
/**
default constructor creates the default complex number a+bi where a=b=0.
*/
public Complex()
{
realNumber = checker;
imagNumber = checker;
}
/**
parameterized constructor creates the complex number a+bi, where b=0.
*/
public Complex(int real)
{
realNumber = real;
imagNumber = checker;
}
/**
parameterized constructor creates the complex number a+bi where a and b are
integers.
*/
public Complex(int real, int imag)
{
realNumber = real;
imagNumber = imag;
}
/**
method returns a new Complex number that represents the sum
of two Complex numbers.
#param cp
#return new summed complex number
*/
public Complex plus(Complex cp)
{
return new Complex(realNumber + cp.realNumber, imagNumber + cp.imagNumber);
}
/**
method returns a new Complex that represents the difference
between two Complex numbers
#param cp
#return difference of two Complex numbers
*/
public Complex minus(Complex cp)
{
return new Complex(realNumber - cp.realNumber, imagNumber - cp.imagNumber);
}
/**
method returns a new Complex that represents the product of
two Complex numbers
#param cp
#return product of two complex numbers
*/
public Complex times(Complex cp)
{
return new Complex(realNumber * cp.realNumber - imagNumber * cp.imagNumber,
realNumber * cp.realNumber + imagNumber * cp.realNumber);
}
/**
method should return a new Complex that is the conjugate of a
Complex number
#param none
#return conjugate of complex number
*/
public Complex conjugate()
{
return new Complex(realNumber, -imagNumber);
}
/**
method returns true if two Complex numbers have the same
real and imaginary; return false otherwise.
#param obj
#return true if two complex numbers are equal, false otherwise
*/
public boolean equals(Object obj)
{
if (obj instanceof Complex)
{
Complex n = (Complex) obj;
return n.realNumber == realNumber && n.imagNumber == imagNumber;
}
return false;
}
/**
method returns a complex number as a String.
uses multiple if statements to check validity
#param none
#return complex number as a string
*/
public String toString()
{
if (imagNumber == checker)
{
return String.valueOf(realNumber);
}
if (realNumber == checker && imagNumber == checker)
{
return String.valueOf(checker);
}
if (realNumber == checker)
{
return imagNumber + "i";
}
if (realNumber != checker && imagNumber < checker)
{
return realNumber + " - " + -imagNumber + "i";
}
if (realNumber != checker && imagNumber > checker)
{
return realNumber + " + " + imagNumber + "i";
}
return "invalid";
}
}
Start of my Stack class
/**
performs all practical Stack operations
#author Cody
*/
public class Stack
{
private Object[] elements;
private int top;
/**
parameterized constructor creates array of Elements with size of size
initializes top to 0
#param size
*/
public Stack(int size)
{
elements = new Object[size];
top = 0;
}
/**
checks to see if the array is empty
#param none
#return true if array is empty, false otherwise.
*/
public boolean isEmpty()
{
return top == 0;
}
/**
checks to see if the array is full
#param none
#return true if array is full, false otherwise.
*/
public boolean isFull()
{
return top == elements.length;
}
/**
returns the item most recently added to the stack. if the array is empty,
returns null
#param none
#return last item added to stack, null if empty array
*/
public Object peek()
{
if (top == 0)
return null;
return elements[top - 1];
}
/**
returns and deletes element most recently added to the stack
#param none
#return element most recently added to stack
*/
public Object pop()
{
return elements[--top];
}
/**
adds item to stack and increments top
#param obj
*/
public void push(Object obj)
{
elements[top++] = obj;
}
/**
returns number of items in stack
#param none
#return number of items in stack
*/
public int size()
{
return elements.length;
}
/**
clears the stack by popping everything in it
#param none
*/
public void clear()
{
for (int i = 0; i < size(); i++)
elements[i] = pop();
}
}

In your evaluate method, you have this piece of code:
int value = Integer.parseInt(token);
operand.push(value);
But when you pop such values , you are converting it to (Complex) in your evaluateTwoOperations method. Hence, you are getting the ClassCastException.
You already have a constructor to help you convert your Integer to Complex class
You could use that.
public Complex(int real)
{
realNumber = real;
imagNumber = checker;
}

Related

Evaluates the given postfix expression with stack

I am working to write code to Evaluate the given postfix expression. I have wrote a code, but one of the junit test doesn´t go through. How should i write that "expr contains too few operands". In the evalute I use a stack.
TODO: help to correct the "evaluate(String expr) throws ExpressionException ()" method so all the test in the testclass goes through.
EDIT: The test that i need help withy is the only in the JUNIT test class.
Interface stack:
/**
* A interface of stack
*/
public interface Stack <T> {
/**
* Adds the element to the top of the stack.
*/
void push (T elem);
/**
* Removes and returns the top element in stack,
* that is the element that was last added.
* Throws an EmptyStackException if stack is empty.
*/
T pop();
/**
* Returns the top element in the stack without removing it.
* Throws an EmptyStackException if stack is empty.
*/
T top();
/**
* Returns the number of elements in stack.
* #return the number of elements.
*/
int size();
/**
* Returns true if the stack is empty.
* #return true.
*/
boolean isEmpty();
}
Linkedlist implements stack:
import java.util.EmptyStackException;
import java.util.NoSuchElementException;
/**
* A singly linked list.
*
*/
public class LinkedList<T> implements Stack <T> {
private ListElement<T> first; // First element in list.
private ListElement<T> last; // Last element in list.
private int size; // Number of elements in list.
/**
* A list element.
*/
private static class ListElement<T>{
public T data;
public ListElement<T> next;
public ListElement(T data) {
this.data = data;
this.next = null;
}
}
/**
* Creates an empty list.
*/
public LinkedList() {
this.first = null;
this.last = null;
this.size = 0;
}
/**
* Inserts the given element at the beginning of this list.
*
* #param element An element to insert into the list.
*/
public void addFirst(T element) {
ListElement<T> firstElement = new ListElement<>(element);
if (this.size == 0){
this.first = firstElement;
this.last = firstElement;
}
else{
firstElement.next = this.first;
this.first = firstElement;
}
this.size ++;
}
/**
* Inserts the given element at the end of this list.
*
* #param element An element to insert into the list.
*/
public void addLast(T element) {
ListElement<T> lastElement = new ListElement<>(element);
if(this.size ==0){
this.first = lastElement;
}
else{
this.last.next = lastElement;
}
this.last = lastElement;
this.size ++;
}
/**
* #return The head of the list.
* #throws NoSuchElementException if the list is empty.
*/
public T getFirst() {
if (this.first != null){
return this.first.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* #return The tail of the list.
* #throws NoSuchElementException if the list is empty.
*/
public T getLast() {
if(this.last != null){
return this.last.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* Returns an element from a specified index.
*
* #param index A list index.
* #return The element at the specified index.
* #throws IndexOutOfBoundsException if the index is out of bounds.
*/
public T get(int index) {
if(index < 0|| index >= this.size){
throw new IndexOutOfBoundsException();
}
else{
ListElement<T>element = this.first;
for(int i = 0; i < index; i++){
element = element.next;
}
return element.data;
}
}
/**
* Removes the first element from the list.
*
* #return The removed element.
* #throws NoSuchElementException if the list is empty.
*/
public T removeFirst() {
if(this.first != null || this.size != 0){
ListElement<T> list = this.first;
this.first = first.next;
size --;
return list.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* Removes all of the elements from the list.
*/
public void clear() {
this.first = null;
this.last = null;
this.size =0;
}
/**
* Adds the element to the top of the stock.
* #param elem
*/
#Override
public void push(T elem) {
ListElement <T> list = new ListElement<>(elem);
if( first == null){
first = list;
last = first;
} else{
list.next = first;
first = list;
}
size ++;
}
/**
* Removes and returns the top element in stack,
* that is the element that was last added.
* Throws an EmptyStackException if stack is empty.
* #return the top element in the stack.
*/
#Override
public T pop(){
if(isEmpty()){
throw new EmptyStackException();
}else{
ListElement <T> list = first;
first = first.next;
size --;
return list.data;
}
}
/**
* returns the top element in the stack without removing it.
* Throws an EmptyStackException if stack is empty.
* #return the top element.
*/
#Override
public T top() {
if(isEmpty()){
throw new EmptyStackException();
}else{
return first.data;
}
}
/**
* Returns the number of elements in the stock
* #return The number of elements in the stock.
*/
public int size() {
return this.size;
}
/**
* Note that by definition, the list is empty if both first and last
* are null, regardless of what value the size field holds (it should
* be 0, otherwise something is wrong).
*
* #return <code>true</code> if this list contains no elements.
*/
public boolean isEmpty() {
return first == null && last == null;
}
/**
* Creates a string representation of this list. The string
* representation consists of a list of the elements enclosed in
* square brackets ("[]"). Adjacent elements are separated by the
* characters ", " (comma and space). Elements are converted to
* strings by the method toString() inherited from Object.
*
* Examples:
* "[1, 4, 2, 3, 44]"
* "[]"
*
* #return A string representing the list.
*/
public String toString() {
ListElement<T> listOfElements = this.first;
String returnString = "[";
while(listOfElements != null) {
returnString += listOfElements.data;
if(listOfElements.next != null){
returnString += ", ";
}
listOfElements = listOfElements.next;
}
returnString += "]";
return returnString;
}
}
Postfix class:
import java.util.Scanner;
import java.util.Stack;
/**
* The Postfix class implements an evaluator for integer postfix expressions.
*
* Postfix notation is a simple way to define and write arithmetic expressions
* without the need for parentheses or priority rules. For example, the postfix
* expression "1 2 - 3 4 + *" corresponds to the ordinary infix expression
* "(1 - 2) * (3 + 4)". The expressions may contain decimal 32-bit integer
* operands and the four operators +, -, *, and /. Operators and operands must
* be separated by whitespace.
*
*/
public class Postfix {
public static class ExpressionException extends Exception {
public ExpressionException(String message) {
super(message);
}
}
/**
* Evaluates the given postfix expression.
*
* #param expr Arithmetic expression in postfix notation
* #return The value of the evaluated expression
* #throws ExpressionException if the expression is wrong
*/
public static int evaluate(String expr) throws ExpressionException {
expr = expr.trim();
String[] tokens = expr.split("\\s+");
if(expr.matches("(\\+)|(\\-)|(\\*)|(\\/)")){
throw new ExpressionException("");
}
LinkedList<Integer> stack = new LinkedList<>();
for(String token: tokens) {
if(isInteger(token)) {
int number = Integer.parseInt(token);
stack.push(number);
}
else if(isOperator(token)) {
String operator = token;
int b = stack.pop();
int a = stack.pop();
if(token.equals("+")){
stack.push(a+b);
} else if (token.equals("-")){
stack.push(a-b);
}
else if(token.equals("/")){
if( b == 0){
throw new ExpressionException("");
}
stack.push(a/b);
} else if(token.equals("*")){
stack.push(a*b);
}
}
else {
throw new ExpressionException("");
}
}
if(stack.size() != 1){
throw new ExpressionException("");
}
int result = stack.pop();
if(stack.isEmpty()) {
throw new ExpressionException("");
}
return result;
}
/**
* Returns true if s is an operator.
*
* A word of caution on using the String.matches method: it returns true
* if and only if the whole given string matches the regex. Therefore
* using the regex "[0-9]" is equivalent to "^[0-9]$".
*
* An operator is one of '+', '-', '*', '/'.
*/
private static boolean isOperator(String s) {
return s.matches("[-+*/]");
}
/**
* Returns true if s is an integer.
*
* A word of caution on using the String.matches method: it returns true
* if and only if the whole given string matches the regex. Therefore
* using the regex "[0-9]" is equivalent to "^[0-9]$".
*
* We accept two types of integers:
*
* - the first type consists of an optional '-'
* followed by a non-zero digit
* followed by zero or more digits,
*
* - the second type consists of an optional '-'
* followed by a single '0'.
*/
private static boolean isInteger(String s) {
return s.matches("(((\\-)*?[1-9](\\d+)*)|(\\-)*?0)");
}
}
Junit class
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
/**
* Test class for Postfix
*
*/
public class PostfixTest {
#Rule public Timeout globalTimeout = Timeout.seconds(5);
#Test
public void evaluateExceptionWhenExprContainsTooFewOperands() {
String[] expressions = {"1 +", " 1 2 + +"};
assertExpressionExceptionOnAll(expressions);
}
}
Your pop() method will throw an exception when the stack is empty (which you can catch) and your isEmpty() method will return true when the stack is empty. You can also use the size() method to check the number of items on the stack. As an example, you can use code like this to check if there are enough values to run your operand:
// ...
else if(isOperator(token)) {
String operator = token;
if (stack.size() < 2) {
throw new ExpressionException("There are not enough values on the stack to perform the operation");
}
int b = stack.pop();
int a = stack.pop();
// ...

Searching a 2D char array for occurrences

I'm hoping to find a bit of direction for this problem I was given. Been banging my head over it for two weeks now. Essentially, I'm to write a function, public static int FindWords(char[][] puzzle) , where given a 2D char array, I can find the amount of times a given set of strings occur. Given:
public static class PuzzleSolver
{
public static string[] DICTIONARY = {"OX","CAT","TOY","AT","DOG","CATAPULT","T"};
static bool IsWord(string testWord)
{
if (DICTIONARY.Contains(testWord))
return true;
return false;
}
}
A 2D Array for instance that is like this:
public static char[][] puzzle = {{'C','A','T'},
{'X','Z','T'},
{'Y','O','T'}};
Would return back 8 for the following instances: (AT, AT, CAT, OX, TOY, T, T, T) because we would be searching horizontally, vertically, diagonally and in reverse for all the same directions.
My approach was to visit each char in the array and then search for all possible directions with the SearchChar function...
public static int FindWords(char[][] puzzle){
int arrayRow = puzzle.length;
int arrayCol = puzzle[0].length;
int found = 0;
for(int i = 0; i < arrayRow; i++){
for(int j = 0; j < arrayCol; j++){
found += SearchChar(i,j);
}
}
return found;
}
Which looks like this:
public static int SearchChar(int row, int col){
if(row < 0 || col < 0 || row > puzzle.length || col > puzzle[0].length)//Is row or col out of bounds?
return 0;
if(IsWord(puzzle[row][col]))
return 1;
return 0;
}
Conceptually, I feel like I need some kind of recursive function to handle this but I can't seem to wrap my head around it. I don't even know if that's the right approach. I've been playing around with StringBuilder appending but I'm still struggling with that too. I think this recursive function would need to take for instance, puzzle[0][0] (or 'C') and see if it is in the dictionary. Followed by puzzle[0][0] + puzzle[0][1] (or 'CA') and then finally puzzle[0][0] + puzzle[0][1] + puzzle[0][2] (or 'CAT'). Then the same would have to be don vertically and diagonally. I'm having trouble trying to get back into the SearchChar function with a position change to append to the original char so that I can see if it is in the DICTIONARY.
Sorry if this is a bit wordy, but I just want to give the impression that I'm actually trying to solve this. Not just some lazy programmer that's copy & pasting some problem up here for someone else to solve. Thanks in advance for any help!
I will show you how to solve this problem step by step.
1. Generating All Possible Words from the given Puzzle
to do this we must start anywhere in the puzzle and move towards all directions (except the previous Point) to generate all possible words;
2. Choosing Suitable Data Structure for Dictionary
I think Trie is a good choice and is suitable for use in such situations.
The most important reason for choosing Trie is that during the search, we can easily test if a word exists in our dictionary or is there any word that starts with the word generated by searching through the puzzle or not.
As a result, we can decide whether or not to continue the search.
This will save us a lot of time and helps to generate words correctly.
otherwise, we'll be stuck in an endless loop...
3. Implementation
there are several implementations for Tire , but I wrote my own CharTrie :
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* #author FaNaJ
*/
public final class CharTrie {
/**
* Pointer to root Node
*/
private final Node root = new Node();
/**
* Puts the specified word in this CharTrie and increases its frequency.
*
* #param word word to put in this CharTrie
* #return the previous frequency of the specified word
*/
public int put(String word) {
if (word.isEmpty()) {
return 0;
}
Node current = root;
for (int i = 0; i < word.length(); i++) {
current = current.getChildren().computeIfAbsent(word.charAt(i), ch -> new Node());
}
return current.getAndIncreaseFrequency();
}
/**
* #param word the word whose frequency is to be returned
* #return the current frequency of the specified word or -1 if there isn't such a word in this CharTrie
*/
public int frequency(String word) {
if (word.isEmpty()) {
return 0;
}
Node current = root;
for (int i = 0; i < word.length() && current != null; i++) {
current = current.getChildren().get(word.charAt(i));
}
return current == null ? -1 : current.frequency;
}
/**
* #param word the word whose presence in this CharTrie is to be tested
* #return true if this CharTrie contains the specified word
*/
public boolean contains(String word) {
return frequency(word) > 0;
}
/**
* #return a CharTrie Iterator over the Nodes in this CharTrie, starting at the root Node.
*/
public Iterator iterator() {
return new Iterator(root);
}
/**
* Node in the CharTrie.
* frequency-children entry
*/
private static final class Node {
/**
* the number of occurrences of the character that is associated to this Node,
* at certain position in the CharTrie
*/
private volatile int frequency = 0;
private static final AtomicIntegerFieldUpdater<Node> frequencyUpdater
= AtomicIntegerFieldUpdater.newUpdater(Node.class, "frequency");
/**
* the children of this Node
*/
private Map<Character, Node> children;
public Map<Character, Node> getChildren() {
if (children == null) {
children = new ConcurrentHashMap<>();
}
return children;
}
/**
* Atomically increments by one the current value of the frequency.
*
* #return the previous frequency
*/
private int getAndIncreaseFrequency() {
return frequencyUpdater.getAndIncrement(this);
}
}
/**
* Iterator over the Nodes in the CharTrie
*/
public static final class Iterator implements Cloneable {
/**
* Pointer to current Node
*/
private Node current;
private Iterator(Node current) {
this.current = current;
}
/**
* Returns true if the current Node contains the specified character in its children,
* then moves to the child Node.
* Otherwise, the current Node will not change.
*
* #param ch the character whose presence in the current Node's children is to be tested
* #return true if the current Node's children contains the specified character
*/
public boolean next(char ch) {
Node next = current.getChildren().get(ch);
if (next == null) {
return false;
}
current = next;
return true;
}
/**
* #return the current frequency of the current Node
*/
public int frequency() {
return current.frequency;
}
/**
* #return the newly created CharTrie Iterator, starting at the current Node of this Iterator
*/
#Override
#SuppressWarnings("CloneDoesntCallSuperClone")
public Iterator clone() {
return new Iterator(current);
}
}
}
and the WordGenerator :
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.function.BiConsumer;
/**
* #author FaNaJ
*/
public final class WordGenerator {
private WordGenerator() {
}
public static void generate(char[][] table, CharTrie.Iterator iterator, BiConsumer<String, Integer> action) {
final ForkJoinPool pool = ForkJoinPool.commonPool();
final VisitorContext ctx = new VisitorContext(table, action);
for (int y = 0; y < table.length; y++) {
for (int x = 0; x < table[y].length; x++) {
pool.invoke(new Visitor(new Point(x, y), null, "", iterator.clone(), ctx));
}
}
}
private static final class VisitorContext {
private final char[][] table;
private final BiConsumer<String, Integer> action;
private VisitorContext(char[][] table, BiConsumer<String, Integer> action) {
this.table = table;
this.action = action;
}
private boolean validate(Point point) {
Object c = null;
try {
c = table[point.getY()][point.getX()];
} catch (ArrayIndexOutOfBoundsException ignored) {
}
return c != null;
}
}
private static final class Visitor extends RecursiveAction {
private final Point current;
private final Point previous;
private final CharTrie.Iterator iterator;
private final VisitorContext ctx;
private String word;
private Visitor(Point current, Point previous, String word, CharTrie.Iterator iterator, VisitorContext ctx) {
this.current = current;
this.previous = previous;
this.word = word;
this.iterator = iterator;
this.ctx = ctx;
}
#Override
protected void compute() {
char nextChar = ctx.table[current.getY()][current.getX()];
if (iterator.next(nextChar)) {
word += nextChar;
int frequency = iterator.frequency();
if (frequency > 0) {
ctx.action.accept(word, frequency);
}
List<Visitor> tasks = new ArrayList<>();
for (Direction direction : Direction.values()) {
Point nextPoint = direction.move(current);
if (!nextPoint.equals(previous) && ctx.validate(nextPoint)) {
tasks.add(new Visitor(nextPoint, current, word, iterator.clone(), ctx));
}
}
invokeAll(tasks);
}
}
}
}
Note that I've used ForkJoinPool and RecursiveAction to speed up the search.
learn more :
https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
http://tutorials.jenkov.com/java-util-concurrent/java-fork-and-join-forkjoinpool.html
http://www.javaworld.com/article/2078440/enterprise-java/java-tip-when-to-use-forkjoinpool-vs-executorservice.html
the rest of classes :
PuzzleSolver
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.stream.Stream;
/**
* #author FaNaJ
*/
public final class PuzzleSolver {
private final CharTrie dictionary;
public enum OrderBy {FREQUENCY_IN_DICTIONARY, FREQUENCY_IN_PUZZLE}
public PuzzleSolver(CharTrie dictionary) {
this.dictionary = dictionary;
}
public CharTrie getDictionary() {
return dictionary;
}
public Stream<Word> solve(char[][] puzzle) {
return solve(puzzle, OrderBy.FREQUENCY_IN_DICTIONARY);
}
public Stream<Word> solve(char[][] puzzle, OrderBy orderBy) {
Stream<Word> stream = null;
switch (orderBy) {
case FREQUENCY_IN_DICTIONARY: {
final Map<String, Integer> words = new ConcurrentHashMap<>();
WordGenerator.generate(puzzle, dictionary.iterator(), words::put);
stream = words.entrySet().stream()
.map(e -> new Word(e.getKey(), e.getValue()));
break;
}
case FREQUENCY_IN_PUZZLE: {
final Map<String, AtomicInteger> words = new ConcurrentHashMap<>();
BiConsumer<String, Integer> action = (word, frequency) -> words.computeIfAbsent(word, s -> new AtomicInteger()).getAndIncrement();
WordGenerator.generate(puzzle, dictionary.iterator(), action);
stream = words.entrySet().stream()
.map(e -> new Word(e.getKey(), e.getValue().get()));
break;
}
}
return stream.sorted((a, b) -> b.compareTo(a));
}
}
http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Point
import java.util.Objects;
/**
* #author FaNaJ
*/
public final class Point {
private final int x;
private final int y;
public Point() {
this(0, 0);
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public int hashCode() {
return x * 31 + y;
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Point that = (Point) obj;
return x == that.x && y == that.y;
}
#Override
public String toString() {
return "[" + x + ", " + y + ']';
}
}
Word
/**
* #author FaNaJ
*/
public final class Word implements Comparable<Word> {
private final String value;
private final int frequency;
public Word(String value, int frequency) {
this.value = value;
this.frequency = frequency;
}
public String getValue() {
return value;
}
public int getFrequency() {
return frequency;
}
#Override
public int hashCode() {
return value.hashCode() * 31 + frequency;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Word that = (Word) o;
return frequency == that.frequency && value.equals(that.value);
}
#Override
public String toString() {
return "{" +
"value='" + value + '\'' +
", frequency=" + frequency +
'}';
}
#Override
public int compareTo(Word o) {
return Integer.compare(frequency, o.frequency);
}
}
Direction
/**
* #author FaNaJ
*/
public enum Direction {
UP(0, 1), UP_RIGHT(1, 1), UP_LEFT(-1, 1),
RIGHT(1, 0), LEFT(-1, 0),
DOWN(0, -1), DOWN_RIGHT(1, -1), DOWN_LEFT(-1, -1);
private final int x, y;
Direction(int x, int y) {
this.x = x;
this.y = y;
}
public Point move(Point point) {
return new Point(point.getX() + x, point.getY() + y);
}
}
4. Test it
/**
* #author FaNaJ
*/
public class Test {
public static String[] DICTIONARY = {"OX", "CAT", "TOY", "AT", "DOG", "CATAPULT", "T", "AZOYZACZOTACXY"};
public static void main(String[] args) {
CharTrie trie = new CharTrie();
for (String word : DICTIONARY) {
trie.put(word);
}
PuzzleSolver solver = new PuzzleSolver(trie);
char[][] puzzle = {
{'C', 'A', 'T'},
{'X', 'Z', 'T'},
{'Y', 'O', 'T'}
};
solver.solve(puzzle, PuzzleSolver.OrderBy.FREQUENCY_IN_PUZZLE).forEach(System.out::println);
}
}
output :
{value='T', frequency=3}
{value='AT', frequency=2}
{value='CAT', frequency=2}
{value='TOY', frequency=2}
{value='OX', frequency=1}
{value='AZOYZACZOTACXY', frequency=1}

NullPointerException while iterating over Binary Tree

Now I'm not sure anybody can really help me with this, since it's a pretty sizable amount of code to go through, but any help would be greatly appreciated. Here is my relevant code:
public class BTree implements Iterable<String> {
/** Left child */
BTree left;
/** Right Child */
BTree right;
/** Comparator to use for sorting */
Comparator<String> comp;
/** Parent node */
BTree parent;
/** String stored in this leaf */
String s;
/** # of iterators currently working on it */
int active = 0;
/** Size of the BTree */
int size;
public void build(Iterable<String> iter, int numStrings) {
if (this.active > 0) {
throw new ConcurrentModificationException();
}
else {
Iterator<String> itr = iter.iterator();
while (numStrings != 0 && itr.hasNext()) {
String s = itr.next();
if (!this.contains(s)) {
this.insert(s);
this.size++;
numStrings--;
}
}
}
}
/**
* Inserts the string into the given BTree
* #param str - String to insert
*/
private void insert(String str) {
if (this.s.equals("")) {
this.s = str;
}
else if (this.comp.compare(str, this.s) > 0) {
if (this.right == null) {
BTree bt = BTree.binTree(this.comp);
bt.s = str;
this.right = bt;
bt.parent = this;
}
else {
this.right.insert(str);
}
}
else if (this.comp.compare(str, this.s) < 0) {
if (this.left == null) {
BTree bt = BTree.binTree(this.comp);
bt.s = str;
this.left = bt;
bt.parent = this;
}
else {
this.left.insert(str);
}
}
}
private class BTreeIterator implements Iterator<String> {
/** Current BTree being iterated over */
BTree current;
/** How many next() calls have there been */
int count;
/** Size of the BTree */
int max;
/** Constructor for BTreeIterator
* #param current
*/
BTreeIterator(BTree current) {
this.current = current;
this.count = 0;
this.max = current.size;
active++;
}
/** Returns true if there is another string to iterate over
* #return boolean
*/
public boolean hasNext() {
if (this.count != this.max) {
return true;
}
else {
active--;
return false;
}
}
/**
* Returns the next string in the iterator
* #return String
*/
public String next() {
if (this.count == 0) {
this.count++;
current = this.current.getLeftMost();
if (this.current.s.equals("")) {
throw new NoSuchElementException();
}
return this.current.s;
}
else if (this.current.right != null) {
this.current = this.current.right.getLeftMost();
this.count++;
return this.current.s;
}
else {
BTree tree = this.current;
while (tree.parent.right == tree) {
tree = tree.parent;
}
this.current = tree.parent;
this.count++;
return this.current.s;
}
}
/** Throws an exception since we aren't removing anything from the trees
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
}
}
The Exception gets thrown at the while (tree.parent.right == tree) line in the next() method of the iterator. The funny thing is, my code has worked just fine with a comparator comparing lexicographically and reverse lexicographically sorting through a file of 24000 words. It only throws the exception when using the following comparator:
class StringWithOutPrefixByLex implements Comparator<String> {
/**
* compares o1 and o2
* #param o1 first String in comparison
* #param o2 second String in comparison
* #return a negative integer, zero, or a positive integer
* as the first argument is less than, equal to, or
* greater than the second.
*/
public int compare(String o1, String o2) {
String s1, s2;
if(o1.length() > 4){
s1 = o1.substring(3);
}
else {
s1 = o1;
}
if(o2.length() > 4){
s2 = o2.substring(3);
}
else {
s2 = o2;
}
return s1.compareTo(s2);
}
}
Even weirder, it works fine with that comparator for the same file up to 199 words, but as soon as I have it build up to 200 words it breaks.
EDIT: I have determined that the Exception is due to the code trying to reference tree.parent.right while tree.parent is null, but I can't figure out WHY it's trying to do that. As far as I can tell, my code should never try to call a null tree.parent, as explained by my comment below.
Well, you do not actually show enough of your code, but, what about the root node of your BTree? What is the value of BTree.parent in the root node? null?
If the root node has a null parent, then, in this while loop, it is likely that :
while (tree.parent.right == tree) {
tree = tree.parent;
}
... will get to the root node, the tree will be set to tree.parent, which is null, and then the while loop test will fail because tree.parent.right will attempt to dereference a null pointer.

NullPointerException infix to postfix java using stack [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Currently I am working on a project using an ArrayStack to change an infix to postfix and evaluating the postfix evaluation. For the first operator that appears when the program reads it, it sends back
java.lang.NullPointerException
at InfixToPostfix.convertString(InfixToPostfix.java:27)
at Postfix.main(Postfix.java:20)
I debugged the program and I know it will have to deal with my push method in ArrayStack. I just don't know how to get rid of NullPointerException.
Here is my ArrayStack class.
import java.util.*;
public class ArrayStack<T> implements StackADT<T>{
private int top = 0;
private static final int DEFAULT_CAPACITY = 70;
private T[] stack;
#SuppressWarnings("unchecked")
public ArrayStack()
{
top = 0;
stack = (T[])(new Object[DEFAULT_CAPACITY]);
}
#SuppressWarnings("unchecked")
public ArrayStack (int initialCapacity)
{
top = 0;
stack = (T[])(new Object[initialCapacity]);
}
public boolean isEmpty()
{
if(top==0)
return true;
else
return false;
}
public T pop() throws StackIsEmptyException
{
T retVal;
if(isEmpty())
throw new StackIsEmptyException("Stack is Empty");
else{
top--;
retVal = stack[top];
}
return retVal;
}
**public void push (T element)
{
if (size() == stack.length)
expandCapacity();
top++;
element = stack[top];
}**
public T peek() throws StackIsEmptyException
{
if (isEmpty())
throw new StackIsEmptyException("Stack is Empty");
return stack[top-1];
}
#SuppressWarnings("unchecked")
private void expandCapacity()
{
T[] larger = (T[])(new Object[stack.length*2]);
for (int index=0; index < stack.length; index++)
larger[index] = stack[index];
stack = larger;
}
#Override
public String toString() {
String result = "";
for (int scan=0; scan < top; scan++)
result = result + stack[scan].toString() + "\n";
return result;
}
#Override
public int size() {
return top;
}
}
InfixToPostfix classe
public class InfixToPostfix {
private ArrayStack<Character> stack;
private String infix;
private String postfix= "";
public InfixToPostfix(String in, ArrayStack<Character> stack) {
infix = in;
this.stack = stack;
}
#SuppressWarnings("unused")
public String convertString (){
for (int i = 0; i< infix.length(); i++){
try {
char curChar = infix.charAt(i);
if(!isOperator(curChar)){
postfix = postfix + curChar;
if (i == (infix.length()-1)){
while(!stack.isEmpty()){
postfix += stack.pop();
}
}
}**else if(stack.isEmpty()&& isOperator(curChar)){
stack.push(curChar);**
}
else if(charPrec(curChar) == 4){
while (!stack.isEmpty() && stack.size() != '('){
postfix += stack.pop();
}
stack.pop();
}else if(!(stack.isEmpty())&&(precident(curChar,stack.peek()))){
stack.push(curChar);
if(charPrec(stack.peek())==3)
stack.push(curChar);
while (!(stack.isEmpty())&&(!precident(curChar,stack.peek()))){
postfix += stack.pop();
}
stack.push(curChar);
}
}
catch (StackIsEmptyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return postfix;
}
/**
* Evaluates the specified postfix expression. If an operand is
* encountered, it is pushed onto the stack. If an operator is
* encountered, two operands are popped, the operation is
* evaluated, and the result is pushed onto the stack.
* #param expr String representation of a postfix expression
* #return int value of the given expression
*/
public int evaluate (String expr)
{
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer (expr);
/* while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
if (isOperator(token))
{
op2 = (stack.pop()).charValue();
op1 = (stack.pop()).charValue();
result = evalSingleOp (token.charAt(0), op1, op2);
stack.push (new Integer(result));
}
else
stack.push (new Integer(Integer.parseInt(token)));
} */
return result;
}
/**
* Determines if the specified token is an operator.
* #param token String representing a single token
* #return boolean true if token is operator
*/
private boolean isOperator (String token)
{
return ( token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/") );
}
/**
* Performs integer evaluation on a single expression consisting of
* the specified operator and operands.
* #param operation operation to be performed
* #param op1 the first operand
* #param op2 the second operand
* #return int value of the expression
*/
private int evalSingleOp (char operation, int op1, int op2)
{
int result = 0;
switch (operation)
{
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
}
return result;
}
private boolean isOperator(char ch) {
if(ch=='/'||ch=='*'||ch=='+'||ch=='-')
return true;
else
return false;
}
private boolean precident(char one, char two) {
if(charPrec(one) >= charPrec(two));
return true;
}
private int charPrec(char ch) {
switch(ch) {
case '-':
return 1;
case '+':
return 1;
case '*':
return 2;
case '/':
return 2;
case '(':
return 3;
case ')':
return 4;
}
return 0; }
}
There are a few problems in your code... heres the ones I see:
when did a size() method ever return a char value? size() is a really bad method name.
The whole ArrayStack<T> implements StackADT<T> class should probably be CharacterStack implments StackADT<Character> which would simplify a lot of things
This line which I believe is on line 27 (where your nullpointer is), has: stack.size() != '(' but that makes little or no sense..... although it won't throw a null-pointer.
you do not indicate which line has the problem - mark it in the actual code so we can see it, and not have to count the lines ourselves.
The code method and variable names make reading it very difficult. Fix up your naming conventions, edit, and retry.
My guess is that if you todied up the code you will find the problem yourself.

Effective algorithm for homework issue

I need to analyze a text that fulfils the following problem:
Generate an output that shows a count of how many times each word occurs in the text. The report should be sorted first by word length, followed a natural sort.
I was docked points for my solution given below. Is there a better solution available? I have not used maps or any collection because we were told that extra credit will be due for those who don't use collections.
My POJO
/**
* An instance of this object represents the string that occurs in a sentence
* and the number of times it occurs in a single string.
*/
public class Word implements Comparable<Word> {
private final String word;
private int counter = 1;
public Word(String word) {
this.word = word;
}
public void incrementCounter() {
this.counter ++;
}
public String getWord() {
return word;
}
public int getCounter() {
return counter;
}
/**
* Overrides the default hashcode function.
*/
#Override
public int hashCode() {
int hashCode = 103034;
hashCode += this.word != null ? this.word.hashCode() ^ 3 : 0;
hashCode += this.counter ^ 2;
return hashCode;
}
/**
* Overrides the default equals function.
*/
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (!(obj instanceof Word)) {
return false;
}
Word otherWord = (Word) obj;
if (this.word != null && this.word.equals(otherWord.getWord())) {
return true;
}
return false;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Word");
sb.append("{word='").append(word).append('\'');
sb.append(", counter=").append(counter);
sb.append('}');
return sb.toString();
}
/**
* The implementation checks for the order of comparison.
* The implementation first compares by presence of word string.
*
* #param w Word to be compared
* #return calculated order of comparison.
*/
#Override
public int compareTo(Word w) {
if (w == null) {
return -1;
}
if (this.word == null && w.getWord() != null) {
return 1;
}
if (this.word != null && w.getWord() == null) {
return -1;
}
return StringUtils.compareString(this.word, w.getWord());
}
}
import java.util.Comparator;
/**
* An instance of this class is responsible for comparing the instances of two word
* instances by comparing against the word string.
*/
public class WordComparator implements Comparator<Word> {
/**
* Compares two instances of words first by length of the word string and then by the
* word itself.
*
* #param firstWord first word to be compared
* #param secondWord second word to be compared
* #return negative number if the first word is less than the second word;
* positive if the first word is greater than the second word; 0 if equal.
*/
#Override
public int compare(Word firstWord, Word secondWord) {
if (firstWord == secondWord) {
return 0;
}
if (firstWord != null && secondWord == null) {
return -1;
}
if (firstWord == null && secondWord != null) {
return 1;
}
return StringUtils.compareString(firstWord.getWord(), secondWord.getWord());
}
}
Utility class.
public class StringUtils {
// Not to be instantiated.
private StringUtils() {}
/**
* Compares the string first by word length and then by string.
*
* #param first First string to be compared.
* #param second Second string to be compared
* #return integer representing the output of comparison.
*/
public static int compareString(String first, String second) {
if (first == second) {
return 0;
}
if (first == null && second != null) {
return 1;
}
if (first != null && second == null) {
return -1;
}
int wordLengthDifference = first.length() - second.length();
if (wordLengthDifference == 0) {
return first.compareTo(second);
}
return wordLengthDifference;
}
}
Main method:
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
/**
* Finds the number of occurrences of word a in given string. The implementation expects
* the input to be passed adsingle string argument.
*/
public class StringWordOccurences {
/**
* Finds the number of occurrences of a word in a string. The implementation relies
* on the following assumptions.
*
* <p>The word is passed as separate strings as in {#code "Hello" "World"} instead of
* a single string {#code "Hello World"}.
*
* #param args Arguments to be sorted by first word length and then by string.
*/
public static void main(String[] args) {
if (args == null || args.length == 0) {
System.out.println("There were no words. The count is 0");
return;
}
// Find the number of unique words and put them in an array.
Comparator<Word> wordComparator = new WordComparator();
Arrays.sort(args, new Comparator<String>() {
#Override
public int compare(String first, String second) {
return StringUtils.compareString(first, second);
}
});
Word [] words = new Word[args.length];
int numberOfUniqueWords = 0;
for (String wordAsString : args) {
Word word = new Word(wordAsString);
int index = Arrays.binarySearch(words, word, wordComparator);
if (index > -1) {
words[index].incrementCounter();
} else {
words[numberOfUniqueWords ++] = word;
}
}
Word [] filteredWords = Arrays.copyOf(words, numberOfUniqueWords);
// The display output.
for (Word word : filteredWords) {
System.out.println(word);
}
}
}
You don't need the binary searches after you have sorted your words in the desired order, because the identical words will be next to each other. Just go over all the words and compare each with the previous one. If they are equal, increment the counter. If they are not equal, you can print the results for the finished previous word right away (no need to store the results in an array). You also don't really need the Word class, you can do it with Strings.
A few points I can think of but obviously these are second guesses...
You have 3 places where there is similar logic for doing the Word compare.
Ditch the Arrays.sort, Arrays.binarySearch and Arrays.copyOf. Do the searching yourself - might be simpler
You could actually sort after you have reduced to unique values

Categories