Unable to push data read from file onto generic stack - java

I am trying to make a generic class called reverser that takes the contents of a text file and reverses the order of the contents. I am required to do this by using the generic stack class provided. I have to make sure that it works for two types, strings, and floats as they have been instantiated in main.
I am aware I can't push int values (as is returned by BufferedInputStream) onto the stack. My question is what may be a solution to this problem, should I instantiate two different versions of the generic stack class, one for strings and one for floats, or is there another solution?
public class project_5
{
public static void main(String[] args) throws Exception
{
Reverser<String> reversePoem = new Reverser<String>();
Reverser<Float> majiGame = new Reverser<Float>();
}
}
class Reverser<E>
{
private Stack<E> tempStack;
int k = 0;
int val = 0;
public Reverser()
{
tempStack = new Stack<E>();
}
void FileToStack(String fileIn) throws Exception
{
E item = null;
try
{
BufferedInputStream readFile = new BufferedInputStream(new FileInputStream(fileIn));
for(k = 0; (val = readFile.read()) != -1; k++)
{
tempStack.push(val);
}
readFile.close();
}
catch(FileNotFoundException e)
{
System.out.print("File: " + fileIn + " Not Found");
}
catch(IOException e)
{
System.out.print("Reached end of file.");
}
}
void StackToFile(String fileIn)
{
try
{
PrintWriter fileOut = new PrintWriter(fileIn);
fileOut.println();
fileOut.close();
}
catch(FileNotFoundException e)
{
}
}
}
//Class Stack ---------------------------------------
class Stack<E>
{
// pointer to first node in stack
private Node<E> top;
// constructor
public Stack()
{
top = null;
}
public boolean isEmpty()
{
return top == null;
}
public void push(E data)
{
if (data == null)
return;
// build a node and place it on the stack
Node<E> newNode = new Node<E>(data);
newNode.next = top;
top = newNode;
}
public E pop()
{
Node<E> temp;
temp = top;
if (isEmpty())
return null;
top = top.next;
return temp.getData();
}
// console display
public String toString()
{
Node<E> p;
String showAll = "";
// Display all the nodes in the stack
for( p = top; p != null; p = p.next )
showAll += p.toString() + "\n";
return showAll;
}
}
Edit: Removed pictures, added code in text format.

I have made a change to your logic where you are reading a file and then putting into the stack,
You have not put your Node class so I have added that accordingly
You need to typecast your value when reading from file
Note: in case of the file contains improper data you will get a casting error, that you need to handle
source.txt
1 2 3 4 5
target.txt
5
4
3
2
1
Code
import java.io.*;
import java.util.Arrays;
public class Test
{
public static void main(String[] args) throws Exception
{
Reverser<String> reversePoem = new Reverser<String>(String.class);
Reverser<Float> majiGame = new Reverser<Float>(Float.class);
majiGame.FileToStack("source.txt");
majiGame.StackToFile("target.txt");
}
}
class Reverser<E>
{
private Stack<E> tempStack;
private Class<E> tClass;
public Reverser(Class<E> tClass)
{
tempStack = new Stack<E>();
this.tClass = tClass;
}
public static <E> E convertInstanceOfObject(String value, Class<E> clazz) {
try {
// add custom casting, casting could be varies as par usage
if (clazz.getName().equals("java.lang.Integer")) {
return (E)Integer.valueOf(value);
} else if (clazz.getName().equals("java.lang.Float")) {
return (E)Float.valueOf(value);
} else if (clazz.getName().equals("java.lang.String")) {
return (E)value;
}
return clazz.cast(value);
} catch(ClassCastException e) {
return null;
}
}
void FileToStack(String fileIn) throws Exception
{
BufferedReader br;
try
{
br = new BufferedReader(new FileReader(fileIn));
String line = null;
while((line = br.readLine()) != null)
{
String[] valueArray= line.split(" ");
for (String v : valueArray) {
E item = convertInstanceOfObject(v, tClass);
tempStack.push(item);
}
}
br.close();
}
catch(FileNotFoundException e)
{
System.out.print("File: " + fileIn + " Not Found");
}
catch(IOException e)
{
System.out.print("Reached end of file.");
}
}
void StackToFile(String fileIn)
{
try
{
PrintWriter fileOut = new PrintWriter(new FileWriter(fileIn));
E d = null;
while (!tempStack.isEmpty()) {
d = tempStack.pop();
fileOut.println(d);
}
fileOut.close();
}
catch(IOException e)
{
}
}
}
class Node<E> {
Node<E> next;
private E data;
public Node(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
}
//Class Stack ---------------------------------------
class Stack<E>
{
// pointer to first node in stack
private Node<E> top;
// constructor
public Stack()
{
top = null;
}
public boolean isEmpty()
{
return top == null;
}
public void push(E data)
{
if (data == null)
return;
// build a node and place it on the stack
Node<E> newNode = new Node<E>(data);
newNode.next = top;
top = newNode;
}
public E pop()
{
Node<E> temp;
temp = top;
if (isEmpty())
return null;
top = top.next;
return temp.getData();
}
// console display
public String toString()
{
Node<E> p;
String showAll = "";
// Display all the nodes in the stack
for( p = top; p != null; p = p.next )
showAll += p.toString() + "\n";
return showAll;
}
}

Related

How do I fix OutOfMemoryError: Java heap space?

Hi I need help fixing this OutOfMemoryError for my WordLadder program. Basically I after being halfway through the input wordladder file which contains the start and end words to create the world ladders it slows down significantly and the error occurs. I believe the error is due to the creation of several stacks without removal of already used ones.
The error occurs at Line: 74 in the WordStack file in the getNewStacks method which, as the name says, is supposed to get new stacks.
Below are all the required files:
Dictionary txt:
https://drive.google.com/file/d/1vl6N4-3IYK86lGxmf0hqP7nX2e0BYrim/view?usp=sharing
input txt:
https://drive.google.com/file/d/1ahHBL0ivqhC0zh24DCFnar03hxTt7Awc/view?usp=sharing
WordLadder main:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordLadder {
public static void main(String args[]) throws FileNotFoundException {
Dictionary dictionary = new Dictionary(new File("dictionary.txt"));
Scanner scan = new Scanner(new File("input.txt"));
while (scan.hasNextLine()) {
String start = scan.next();
String stop = scan.next();
System.out.println(findLadder(start, stop, dictionary));
}
}
static String findLadder(String start, String end, Dictionary dictionary) {
if (!dictionary.contains(start) || !dictionary.contains(end)) {
return "No word ladder between \"" + start + "\" and \"" + end + "\".";
}
if (start.equals(end)) return start + " " + end;
LinkedList stackQueue = new LinkedList();
stackQueue.enqueue(new WordStack(start, end));
boolean continueSearch;
boolean success = false;
WordStack ladder = new WordStack();
do {
int queueSize = stackQueue.size();
continueSearch = false;
for (int stackIndex = 0; stackIndex < queueSize; stackIndex++) {
LinkedList newStacks = ((WordStack) stackQueue.dequeue()).getNewStacks(dictionary);
if (newStacks.size > 0) {
while (newStacks.size() > 0) {
WordStack next = (WordStack) newStacks.dequeue();
if (next.success()) {
success = true;
ladder = next;
break;
}
stackQueue.enqueue(next);
}
continueSearch = true;
}
if (success) break;
}
if (success) break;
} while (continueSearch);
if (success) return ladder.toString();
else return "No word ladder between \"" + start + "\" and \"" + end + "\".";
}
}
WordStack (location of error line 74) :
public class WordStack {
LinkedList words;
String targetWord;
boolean success;
WordStack() {
words = new LinkedList();
targetWord = "";
success = false;
}
WordStack(LinkedList list, String target) {
words = list;
targetWord = target;
success = false;
}
WordStack(String startWord, String target) {
words = new LinkedList();
words.push(startWord);
targetWord = target;
success = false;
}
int size() {
return words.size();
}
void push(String word) {
words.push(word);
}
void add(String word) {
push(word);
}
String pop() {
if (size() < 1) return null;
return (String) words.pop();
}
String topWord() {
return (String) words.peek();
}
WordStack deepCopy() {
return new WordStack(words.hardCopy(), targetWord);
}
void markSuccess() {
success = true;
}
boolean success() {
return success;
}
boolean contains(String word) {
WordStack compare = deepCopy();
while (compare.size() > 0) {
if (word.equals(compare.pop())) return true;
}
return false;
}
LinkedList getNewStacks(Dictionary dictionary) {
LinkedList stacks = new LinkedList();
for (int letterPos = 0; letterPos < topWord().length(); letterPos++) {
for (char letter = 'a'; letter <= 'z'; letter++) {
String newWord = topWord().substring(0, letterPos) + letter + topWord().substring(letterPos + 1, topWord().length());
if (dictionary.contains(newWord) && !contains(newWord)) {
WordStack newStack = deepCopy();
newStack.push(newWord);
if (newWord.equals(targetWord)) newStack.markSuccess();
stacks.enqueue(newStack);
}
}
}
return stacks;
}
public String toString() {
String returnString = "";
for (int index = size() - 1; index >= 0; index--) {
returnString += (String) words.getPeek(index) + " ";
}
return returnString;
}
}
Node class:
public class Node {
public Object data;
Node next;
Node() {
data = null;
next = null;
}
Node(Object data) {
this.data = data;
next = null;
}
Object get() {
return data;
}
void set(Object data) {
this.data = data;
}
Node getNextPtr() {
return next;
}
void setNextPtr(Node next) {
this.next = next;
}
public String toString() {
return "" + data;
}
}
LinkedList:
public class LinkedList {
Node head;
Node tail;
int size;
LinkedList() {
head = null;
tail = null;
size = 0;
}
LinkedList hardCopy() {
LinkedList copy = new LinkedList();
if(size() < 1) return copy;
Node current = head;
while(current.getNextPtr() != null) {
copy.addEnd(current.get());
current = current.getNextPtr();
}
copy.addEnd(current.get());
return copy;
}
void iterateHead() {
head = head.getNextPtr();
size--;
}
void addEnd(Object newObj) {
enqueue(newObj);
}
void add(Object newObj) {
Node newNode = new Node(newObj);
if(size == 0) {
head = newNode;
}
else {
newNode.setNextPtr(head);
head = newNode;
}
size++;
}
Object peek() {
return head.get();
}
void push(Object newObj) {
add(newObj);
}
void enqueue(Object newObj) {
Node newNode = new Node(newObj);
if(size < 1) {
head = newNode;
tail = newNode;
} else {
tail.setNextPtr(newNode);
tail = newNode;
}
size++;
}
Object pop() {
Node pop = head;
if(size > 1) {
head = head.getNextPtr();
size--;
return pop.get();
}
else if(size == 1) {
size--;
head = null;
return pop.get();
}
else return null;
}
Object dequeue() {
if(size < 1) return null;
Node dequeueNode = head;
if(size > 1) {
iterateHead();
}
else {
head = null;
tail = null;
size--;
}
return dequeueNode.get();
}
int size() {
return size;
}
Object getPeek(int index) {
if(index >= size) return null;
Node current = head;
for(int i = 0; i < index; i++) {
current = current.getNextPtr();
}
Object data = current.get();
return data;
}
}
I do apologize for the amount of required code for the program to run.

How to fix Stack Overflow from recursive getHeight method

When I run my code for a method calculating the height of a binary search tree, it results in a Stack Overflow error, but only for trees with more than one node (BSTElements in my program). I have read that this is due to a faulty recursive call, but cannot identify the problem in my code.
public int getHeight() {
return getHeight(this.getRoot());
}
private int getHeight(BSTElement<String,MorseCharacter> element) {
int height=0;
if (element == null) {
return -1;
}
int leftHeight = getHeight(element.getLeft());
int rightHeight = getHeight(element.getRight());
if (leftHeight > rightHeight) {
height = leftHeight;
} else {
height = rightHeight;
}
return height +1;
}
Here is full code:
public class MorseCodeTree {
private static BSTElement<String, MorseCharacter> rootElement;
public BSTElement<String, MorseCharacter> getRoot() {
return rootElement;
}
public static void setRoot(BSTElement<String, MorseCharacter> newRoot) {
rootElement = newRoot;
}
public MorseCodeTree(BSTElement<String,MorseCharacter> element) {
rootElement = element;
}
public MorseCodeTree() {
rootElement = new BSTElement("Root", "", new MorseCharacter('\0', null));
}
public int getHeight() {
return getHeight(this.getRoot());
}
private int getHeight(BSTElement<String,MorseCharacter> element) {
if (element == null) {
return -1;
} else {
int leftHeight = getHeight(element.getLeft());
int rightHeight = getHeight(element.getRight());
if (leftHeight < rightHeight) {
return rightHeight + 1;
} else {
return leftHeight + 1;
}
}
}
public static boolean isEmpty() {
return (rootElement == null);
}
public void clear() {
rootElement = null;
}
public static void add(BSTElement<String,MorseCharacter> newElement) {
BSTElement<String, MorseCharacter> target = rootElement;
String path = "";
String code = newElement.getKey();
for (int i=0; i<code.length(); i++) {
if (code.charAt(i)== '.') {
if (target.getLeft()!=null) {
target=target.getLeft();
} else {
target.setLeft(newElement);
target=target.getLeft();
}
} else {
if (target.getRight()!=null) {
target=target.getRight();
} else {
target.setRight(newElement);
target=target.getRight();
}
}
}
MorseCharacter newMorseChar = newElement.getValue();
newElement.setLabel(Character.toString(newMorseChar.getLetter()));
newElement.setKey(Character.toString(newMorseChar.getLetter()));
newElement.setValue(newMorseChar);
}
public static void main(String[] args) {
MorseCodeTree tree = new MorseCodeTree();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (line != null) {
String[] output = line.split(" ");
String letter = output[0];
MorseCharacter morseCharacter = new MorseCharacter(letter.charAt(0), output[1]);
BSTElement<String, MorseCharacter> bstElement = new BSTElement(letter, output[1], morseCharacter);
tree.add(bstElement);
line = reader.readLine();
System.out.println(tree.getHeight());
}
reader.close();
} catch (IOException e) {
System.out.println("Exception" + e);
}
There doesn't appear to be anything significantly wrong1 with the code that you have shown us.
If this code is giving a StackOverflowException for a small tree, that most likely means that your tree has been created incorrectly and has a cycle (loop) in it. If your recursive algorithm encounters a cycle in the "tree" it will loop until the stack overflows2.
To be sure of this diagnosis, we need to see an MVCE which includes all code needed to construct an example tree that exhibits thie behavior.
1 - There is possibly an "off by one" error in the height calculation, but that won't cause a stack overflow.
2 - Current Java implementations do not do tail-call optimization.

FileSystem Implementation, Listing File Path through Binary Search Tree

I'm working on a FileSystem implementation, and I'm having trouble with my Binary Search Tree locate method. Right now the way I have it structured. It will add additional files or something else that I'm unable to figure out.
As an example, I have the tree:
/
/ \
a b
/ / \
c h q
/
x
If the user inputs locate h, my program will output /acxh.
When the user inputs locate h, the output SHOULD be /bh
Here is my FileSystem class:
import java.io.IOException;
import java.util.ArrayList;
public class FileSystem {
private Directory root;
private Directory wDir;
private ArrayList<File> files = new ArrayList<File>();
// Constructor
public FileSystem() {
}
// Constructor with parameters
public FileSystem(Directory root) {
this.root = root;
wDir = root;
files.add(root);
}
// Returns the FileSystem's files
public ArrayList<File> getFiles() {
return files;
}
// Returns the working directory
public Directory getWDir() {
return wDir;
}
// Sets the working directory
public void setWDir(Directory d) {
wDir = d;
}
// Returns the root file. This will always be / in our program
public File getRoot() {
return root;
}
public File getFile(File f, String name) {
if (f.isDirectory()) {
for (File c : ((Directory) f).getChildren()) {
if (c.getName().equals(name))
return c;
}
}
return null;
}
// Currently only used in cat method, getFile is better
File findFile(File f, String name) {
if (f.getName().equals(name))
return f;
File file = null;
if (f.isDirectory()) {
for (File c : ((Directory) f).getChildren()) {
file = findFile(c, name);
if (file != null)
break;
}
}
return file;
}
// Returns true if file is found
boolean isFile(String name) {
File file = null;
file = getFile(wDir, name);
if (file != null) {
return true;
}
return false;
}
// Creates Directory
public void mkdir(String path) {
files.add(new Directory(path));
int size = files.size();
// Sets the parent
files.get(size - 1).setParent(wDir);
// Sets the child
wDir.addChild(files.get(size - 1));
}
// Changes working directory
public void cd(String s) {
if (s.equals("..")) {
if (wDir != root) {
wDir = wDir.getParent();
}
} else if (s.equals("/")) {
wDir = root;
} else {
wDir = (Directory) getFile(wDir, s);
}
}
// Provides absolute filename
public void pwd() {
if (wDir == root) {
System.out.println("/");
} else {
System.out.println(wDir.getPath());
}
}
// Lists children of current working directory
public void ls() {
ArrayList<File> children = wDir.getChildren();
if (children != null) {
for (int i = 0; i < children.size(); i++) {
String childName = children.get(i).getName();
System.out.print(childName + " ");
}
}
}
// Lists children of file(s) inputted by user
public void ls(File f) {
if (f instanceof TextFile) {
System.out.println(f.getPath());
} else {
ArrayList<File> children = ((Directory) f).getChildren();
if (children != null) {
for (int i = 0; i < children.size(); i++) {
String childName = children.get(i).getName();
System.out.print(childName + " ");
}
}
}
}
public void recLS(File f, String location) {
System.out.println(location + ":");
ls(f);
System.out.println("");
if (f.isDirectory()) {
ArrayList<File> children = ((Directory) f).getChildren();
for (File c : children) {
location += "/" + c.getName();
}
for (File c : children) {
recLS(c, location);
}
}
}
// Creates a TextFile or edit's TextFile's content if already exists in the
// tree
public void edit(String name, String content) {
files.add(new TextFile(name, content));
// Setting TextFile parent
files.get(files.size() - 1).setParent(wDir);
// Setting Parent's child
wDir.addChild(files.get(files.size() - 1));
}
// Prints the content of TextFile
public void cat(String name) {
File f = findFile(root, name);
System.out.println(((TextFile) f).getContent());
}
public void updatedb(Indexer i) throws IOException {
i.index(files);
}
public String locate(String s, Indexer i) {
return i.locate(s);
}
}
Here is my Indexer class:
import java.io.*;
import java.util.*;
class Entry implements Comparable<Entry> {
String word;
ArrayList<Integer> page = new ArrayList<Integer>();
Entry(String word) {
this.word = word;
}
public int compareTo(Entry e) {
return word.compareTo(e.word);
}
}
class Indexer {
private BinarySearchTree<Entry> bst;
public void index(ArrayList<File> files) throws IOException {
bst = new BinarySearchTree<Entry>();
int fileCount = 1;
for (int i = 0; i < files.size(); i++) {
String name = files.get(i).getName();
indexName(name, fileCount++);
}
}
private void indexName(String name, int fileCount) {
Entry e = new Entry(name);
Entry r = bst.find(e);
if (r != null) {
r.page.add(fileCount);
} else {
e.page.add(fileCount);
bst.add(e);
}
}
public String locate(String s) {
Entry e = new Entry(s);
ArrayList<String> path = new ArrayList<String>();
bst.locateHelper(e, bst.root, path);
String word = "";
for (int i = 0; i < path.size(); i++) {
word += path.get(i);
}
return word;
}
}
Here is my BinarySearchTree class:
import java.util.ArrayList;
public class BinarySearchTree<E extends Comparable> extends BinaryTree<E> {
private boolean addReturn;
private E deletedItem;
boolean add(E item) {
root = add(root, item);
return addReturn;
}
private Node<E> add(Node<E> n, E item) {
if (n == null) {
addReturn = true;
return new Node<E>(item);
} else if (item.compareTo(n.data) == 0) {
addReturn = false;
return n;
} else if (item.compareTo(n.data) < 0) {
n.leftChild = add(n.leftChild, item);
return n;
} else {
n.rightChild = add(n.rightChild, item);
return n;
}
}
public E find(E target) {
return find(target, root);
}
private E find(E target, Node<E> node) {
if (node == null) {
return null;
}
int result = target.compareTo(node.data);
if (result == 0) {
return node.data;
}
if (result < 0) {
return find(target, node.leftChild);
}
return find(target, node.rightChild);
}
public String locateHelper(Entry e, Node<Entry> node, ArrayList<String> path) {
if (node == null) {
return null;
}
int result = e.compareTo(node.data);
if (result == 0) {
path.add(node.data.word);
return node.data.word;
}
if (result < 0) {
path.add(node.data.word);
return locateHelper(e, node.leftChild, path);
}
path.add(node.data.word);
return locateHelper(e, node.rightChild, path);
}
}
I apologize for having a lot of code in the post, I know I'm supposed to keep it minimal, but I'm sure you will need to look at these 3 classes at least to provide some help. If anything else is needed just let me know and I'll edit this post to provide it.

Array Index Out of bounds exception JAVA

I tried running this code that is a move-to-front encoder, but I get this exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at MTFencoder.main(MTFencoder.java:10)
Could someone explain why this happens?
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.IOException;
public class MTFencoder {
public static void main(String[] args) {
String filename = args[0];
WordList wordList = new WordList();
try {
String line;
BufferedReader br = new BufferedReader(new FileReader(filename));
StringTokenizer st;
int index;
while ((line = br.readLine()) != null) {
st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
String currentword = st.nextToken();
if (wordList.hasElement(currentword)) {
index = wordList.Index(currentword);
wordList.remove(currentword);
wordList.add(currentword);
System.out.println(Integer.toString(index));
} else {
wordList.add(currentword);
System.out.println("0" + currentword);
}
}
}
} catch (IOException e) {
}
}
}
class Node {
private String word;
private Node next;
public Node(String w) {
word = w;
next = null;
}
public String getWord() {
return word;
}
public Node getNext() {
return next;
}
public void setNext(Node n) {
next = n;
}
}
class WordList {
Node head;
public WordList() {
}
public void add(String w) {
Node n = new Node(w);
n.setNext(head);
head = n;
}
public int length() {
Node tmp = head;
int count = 0;
while (tmp != null) {
count++;
tmp = tmp.getNext();
}
return count;
}
public boolean hasElement(String w) {
Node tmp = head;
while (tmp != null) {
if (tmp.getWord().equals(w)) return true;
tmp = tmp.getNext();
}
return false;
}
public void remove(String w) {
if (!hasElement(w)) return;
if (head.getWord().equals(w)) {
head = head.getNext();
return;
}
Node tmp = head;
while (!(tmp.getNext().getWord().equals(w))) tmp = tmp.getNext();
tmp.setNext(tmp.getNext().getNext());
}
public void dumpList() {
for (Node tmp = head; tmp != null; tmp = tmp.getNext())
System.out.println(" >> " + tmp.getWord());
}
public int Index(String w) {
int counter = 1;
Node temp = head;
while (!(temp.getWord().equals(w))) {
counter++;
temp = temp.getNext();
}
return counter++;
}
}
The program expects command line arguments. You aren't passing it.
The program needs to be run as java MTFencoder fileyouwanttoprocess. You aren't passing the filename parameter.
This is line 10
String filename = args[0];
args[0] is the first command line argument - you aren't passing command line arguments.

stack trace in code

I was wondering how I would add a trace to the stack of this code that converts infix to postix for expressions.
class Node {
public Object data;
public Node next;
public Node () {
data =' '; next = null; }
public Node (Object val) {
data = val; next = null; }
}
public class LinkStack {
private Node top;
public LinkStack() {
top = null; }
public boolean empty(){
return top == null; }
public boolean full(){
return false;
}
public void push(Object e){
Node tmp = new Node(e);
tmp.next = top;
top = tmp;
}
public Object pop(){
Object e = top.data;
top = top.next;
return e;
}
public Object peek(){
Object e = top.data;
return e;
}
public void matching(String x)
{
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
if(c=='(')
S.push(c);
else
{
if(c==')')
if(S.empty())
System.out.println("NOT MATCHING !!!");
else
S.pop();
}
}
if(!S.empty())
System.out.println("NOT MATCHING !!!");
else
System.out.println("MATCHING !!!");
}
public void Evaluation(String x)
{
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
String s="0"+c;
if(c=='+')
{
int z=Integer.parseInt((String)S.pop())+Integer.parseInt((String)S.pop());
S.push(Integer.toString(z));
}
else if(c=='*')
{
int z=Integer.parseInt((String)S.pop())*Integer.parseInt((String)S.pop());
S.push(Integer.toString(z));
}
else if(c=='/')
{ int u=Integer.parseInt((String)S.pop());
int z=Integer.parseInt((String)S.pop())/u;
S.push(Integer.toString(z));
}
else if(c=='-')
{ int u=Integer.parseInt((String)S.pop());
int z=Integer.parseInt((String)S.pop())-u;
S.push(Integer.toString(z));
}
else
S.push(s);
}
System.out.println("THE POSTFIX = "+x);
System.out.println("THE RESULT = "+S.pop());
}
public void postfix(String x)
{
String output="";
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
if(c==('+')||c==('*')||c==('-')||c==('/'))
{while(!S.empty() && priority(S.peek())>= priority(c))
output+=S.pop();
S.push(c);
System.out.println(output);
}
else if(c=='(')
{
S.push(c);
}
else if(c==')')
{
while(!S.peek().equals('('))
output+=S.pop();
S.pop();
System.out.println(output);
}
else
{
output+=c;
System.out.println(output);
}
}
while(!S.empty())
output+=S.pop();
System.out.println("THE INFIX = "+x);
System.out.println("THE POSTFIX = "+output);
}
public int priority(Object x)
{
if(x.equals('+')||x.equals('-'))
return 1;
else if(x.equals('*')||x.equals('/'))
return 2;
else
return 0;
}
public static void main(String args[])
{
LinkStack s=new LinkStack();
s.postfix("x*y–z+(a–c/d)");
System.out.println("------------------------------------------");
s.matching("x*y–z+(a–c/d)");
System.out.println("------------------------------------------");
}
}
I am pretty much wanting to follow the contents of the stack throughout the conversion
There's no rocket science solution to this.
Just add System.err.println(...) calls at the relevant places. Or if you were doing this in production code (heaven forbid!) you might use a Logger instead of System.err.
(For the record, the term "stack trace" normally means a trace of a program's call stack, not a trace of what happens to some application-specific stack data structure. You might want to choose your terminology a little more carefully next time.)

Categories

Resources