EDIT: I may have fixed it by making the instance variable static? If so, why does this fix it? This was something my prof glossed over in my intro to OOP class, so I never really learned about it.
so, I'm not sure if I'm using terrible coding practice and just don't realize it, but I'm having a single crippling issue with my program, despite this one issue, everything appears to be running fine.
This program takes strings from an argument file and executes the commands based on the instructions. However, when I issue the command "x = x + 5" I experience a crippling issue.
My class titled Work creates another instance of my other class Read. When it does this, the ArrayList that I define at the top of Read is overwritten with a new instance, and thus, deletes the whole list of variables. I'm unable to find a way to make the initialization execute only once. Where am I going wrong?
Work:
import java.util.*;
public class Work {
static int Precedence(char ch){
switch (ch){
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
}
return -1;
}
String infixConverter(String infix){
Variable tvar = new Variable(); //consider removing these~
Read reader = new Read();
String pfix = new String("");
Stack<Character> stack = new Stack<>();
for (int i=0; i<infix.length(); ++i) {
char curr = infix.charAt(i);
// if (Character.isLetterOrDigit(curr)||curr==' ') {
if (Character.isDigit(curr)||curr==' ') {
pfix += curr;
}
else if (Character.isLetter(curr)){
// Read reader = new Read();
if (reader.varExists(curr)){
// Variable tvar = new Variable();
int n = reader.getIndex(curr);
tvar = reader.vars.get(n);
pfix += tvar.getValue();
}
else{
//error
}
//implement this below
//check for letter within the string, if the string is
}
else if (curr == '('){
stack.push(curr);
}
else if (curr == ')'){
while (!stack.isEmpty() && stack.peek() != '(') {
pfix += stack.pop();
}
if (!stack.isEmpty() && stack.peek() != '(') {
return "Invalid Expression"; // invalid expression
}
else {
stack.pop();
}
}
else {
while (!stack.isEmpty() && Precedence(curr) <=
Precedence(stack.peek())) {
pfix += stack.pop();
}
stack.push(curr);
}
}
while (!stack.isEmpty()) {
pfix += stack.pop();
}
int sol = postfixEvaluation(pfix);
pfix = Integer.toString(sol);
return pfix;
}
Integer postfixEvaluation(String pfix){
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < pfix.length(); i++){
char curr = pfix.charAt(i);
if(curr == ' '){
continue;
}
else if(Character.isDigit(curr)){
int num = 0;
while(Character.isDigit(curr)){
num = num*10 + (int)(curr-'0');
i++;
if (i==pfix.length()){break;}
curr = pfix.charAt(i);
}
i--;
stack.push(num);
//include variables and be able to insert them into here
}
else{
int val1 = stack.pop();
int val2 = stack.pop();
switch(curr){
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2-val1);
break;
case '/':
stack.push(val2/val1);
break;
case '%':
stack.push(val2%val1);
break;
case '*':
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
}
Read:
import java.util.*;
public class Read {
ArrayList<Variable> vars = new ArrayList<Variable>();//FIX THIS SHIT AHHHHHHHHH
Variable tempvar = new Variable();
Work eval = new Work();
private int lnNum = 1;
private String arg="";
public void thing() {
String thing,thing2;
if (arg.contains("print")){
String real="";
int i = arg.indexOf('t');
if (i!=4){}//error
thing = arg.substring(0,i);
if (thing!="print"){}//error
thing2 = arg.substring(i+2,arg.length());
real = eval.infixConverter(thing2);
System.out.println(real);
}
else if (arg.contains("read")){
Scanner in = new Scanner(System.in);
int i = arg.indexOf('d');
if (i!=3){}//error
thing = arg.substring(0,i+1);
if (thing!="read"){}//error
thing2 = arg.substring(i+2,arg.length());
char c2 = thing2.charAt(0);
if (thing2.length()>1){}//error
System.out.println("Enter a value for "+thing2+": ");
String vv = in.nextLine();
vv = eval.infixConverter(vv);
int vvv = Integer.parseInt(vv);
tempvar.setValue(c2, vvv);
vars.add(tempvar);
}
else if (arg.contains("=")){
int i = arg.indexOf('=');
int tempval;
thing = arg.substring(0,i-1);
thing2 = arg.substring(i+2,arg.length());
if(thing.length()>1){}//error
thing2=eval.infixConverter(thing2);
char c = thing.charAt(0);
if (vars.contains(thing)){
tempval = Integer.parseInt(thing2);
tempvar.setValue(c,tempval);
int f = vars.indexOf(thing);
}
else if(Character.isLetter(c)){
tempval = Integer.parseInt(thing2);
tempvar.setValue(c,tempval);
vars.add(tempvar);
}
else{
//error
}
}
else{
}
}
boolean varExists(char c){
for (int i = 0; i<vars.size(); i++){
tempvar = vars.get(i);
if (tempvar.getTitle()==c){
return true;
}
}
return false;
}
int getIndex(char c) {
for (int i = 0; i <= vars.size(); i++) {
tempvar = vars.get(i);
if (tempvar.getTitle() == c) {
return i;
}
}
return -1;
}
int inLineNum(){
lnNum++;
return lnNum;
}
void setArg(String c){
arg=c;
}
}
Related
So i have this function EDIT:Whole program as requested
//This is a java program to construct Expression Tree using Infix Expression
import java.io.*;
public class Infix_Expression_Tree
{
public static void main(String args[]) throws IOException
{
String result="";
File vhod = new File(args[0]);
try{
BufferedReader reader = new BufferedReader(new FileReader(vhod));
Tree t1 = new Tree();
String a = reader.readLine();
t1.insert(a);
t1.traverse(1,result);
System.out.println("rez "+ result);
ch = reader.readLine();
}catch(IOException e){
e.printStackTrace();
}
}
}
class Node
{
public char data;
public Node leftChild;
public Node rightChild;
public Node(char x)
{
data = x;
}
public void displayNode()
{
System.out.print(data);
}
}
class Stack1
{
private Node[] a;
private int top, m;
public Stack1(int max)
{
m = max;
a = new Node[m];
top = -1;
}
public void push(Node key)
{
a[++top] = key;
}
public Node pop()
{
return (a[top--]);
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Stack2
{
private char[] a;
private int top, m;
public Stack2(int max)
{
m = max;
a = new char[m];
top = -1;
}
public void push(char key)
{
a[++top] = key;
}
public char pop()
{
return (a[top--]);
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Conversion
{
private Stack2 s;
private String input;
private String output = "";
public Conversion(String str)
{
input = str;
s = new Stack2(str.length());
}
public String inToPost()
{
for (int i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
switch (ch)
{
case '+':
gotOperator(ch, 2);
break;
case '*':
gotOperator(ch,1);
break;
case '/':
gotOperator(ch, 3);
break;
case '(':
s.push(ch);
break;
case ')':
gotParenthesis();
//s.pop();
break;
default:
//gotOperator(ch, 0);
//break;
output = output + ch;
}
}
while (!s.isEmpty())
output = output + s.pop();
//System.out.println("to je output iz inToPost " +output);
return output;
}
private void gotOperator(char opThis, int prec1)
{
while (!s.isEmpty())
{
char opTop = s.pop();
if (opTop == '(')
{
s.push(opTop);
break;
} else
{
int prec2;
if (opTop == '+')
prec2 = 2;
else if(opTop=='*')
prec2=1;
else
prec2 = 3;
if (prec2 <= prec1)
{
s.push(opTop);
break;
} else
output = output + opTop;
}
}
s.push(opThis);
}
private void gotParenthesis()
{
while (!s.isEmpty())
{
char ch = s.pop();
if (ch == '(')
break;
else
output = output + ch;
}
}
}
class Tree
{
private Node root;
public Tree()
{
root = null;
}
public void insert(String s)
{
Conversion c = new Conversion(s);
s = c.inToPost();
Stack1 stk = new Stack1(s.length());
s = s + "#";
int i = 0;
char symbol = s.charAt(i);
Node newNode;
while (symbol != '#')
{
if (symbol >= '0' && symbol <= '9' || symbol >= 'A'
&& symbol <= 'Z' || symbol >= 'a' && symbol <= 'z')
{
newNode = new Node(symbol);
stk.push(newNode);
} else if (symbol == '+' || symbol == '/'
|| symbol == '*')
{
Node ptr1=null;
Node ptr2=null;
//if(!stk.isEmpty()){
ptr1 = stk.pop();
if(!stk.isEmpty()){
ptr2 = stk.pop();
}
//}
newNode = new Node(symbol);
newNode.leftChild = ptr2;
newNode.rightChild = ptr1;
stk.push(newNode);
}
/*else if(symbol=='/'){
Node ptr = stk.pop();
newNode = new Node(symbol);
newNode.leftChild = ptr;
newNode.rightChild=null;
stk.push(newNode);
}*/
symbol = s.charAt(++i);
}
root = stk.pop();
}
public void traverse(int type,String result)
{
System.out.println("Preorder Traversal:- ");
preOrder(root,result);
}
private void preOrder(Node localRoot, String result)
{
if(root==null){
return;
}
if (localRoot != null)
{
if(localRoot.data == '/'){
preOrder(localRoot.leftChild,result);
result=result + localRoot.data;
//StringBuilder stringBuilder1 = new StringBuilder();
//stringBuilder1.append(result).append(localRoot.data);
System.out.println(result);
//localRoot.displayNode();
preOrder(localRoot.rightChild,result);
return;
}else{
//System.out.println("trenutni root je" );
//localRoot.displayNode();
result=result + localRoot.data;
// StringBuilder stringBuilder1 = new StringBuilder();
//stringBuilder1.append(result).append(localRoot.data);
System.out.println(result);
preOrder(localRoot.leftChild,result);
//result=result + localRoot.data;
//System.out.print(root.data);
preOrder(localRoot.rightChild,result);
//System.out.print(root.data);
//preOrder(localRoot.rightChild);
return;
}
}
}
}
my problem with it is that with localRoot.DisplayNode() i get the result i want. But when i add the same thing to the String result it adds data, until i get to leaf of the tree(leaf doesnt have left/right child) so it returns to previous recursive call, and goes to right child, here somewhere the leaf(from which we came back) isnt in String anymore. How do i fix this?
String is defined in main method
Task is to allocate from bulk of numbers (200k total) Elite and Premium ones. Elite means number is very beautiful and expensive, Premium means more-less beautiful.
My solution works, but it is very slow. To process 200k numbers takes about 40 minutes! Problem is that I have to generate thousands of Regex patterns using masks and then process thousands of numbers through thousands of patterns!
Patterns looks like patternX, patternXY, patternAB, patternABC, patternXAB, patternXABC, patternXYZ, patternXYAB, patternXYAB, for example:
super.patternXYZ = "^\\d+XXYYZZ$|^\\d+ZZXYXY$|^\\d+YXXYYZZ..$";
super.patternXYAB = "^\\d+ABXXYY$|^\\d+ABXYXY$";
Where all the letters are represent mask of numbers: XXYY mathces 4488 or 9933 (X<>=Y) and AABB matches serial sequences like 3344 or 7788 (A+1=B)
Matching occurs by following:
#Override
public Set<String> performCollect() {
for (String number : numbers) {
if (isPatternXMatches(number)) {
result.add(number);
} else if (isPatternXYMatches(number)) {
result.add(number);
}
...
}
return result;
}
Where Regex patterns are being generated for every single match and match performs:
protected boolean isPatternXYZMatches(String number) {
for (int X = 0; X < 10; X++) {
for (int Y = 0; Y < 10; Y++) {
for (int Z = 0; Z < 10; Z++) {
Pattern pattern = Pattern.compile(patternXYZ.replace("X", String.valueOf(X)).replace("Y", String.valueOf(Y)).replace("Z", String.valueOf(Z)));
Matcher matcher = pattern.matcher(number);
if (matcher.find()) {
return true;
}
}
}
}
return false;
}
protected boolean isPatternXYABMatches(String number) {
for (int X = 0; X < 10; X++) {
for (int Y = 0; Y < 10; Y++) {
for (int A = 0, B = 1; B < 10; A++, B++) {
Pattern pattern = Pattern.compile(patternXYAB.replace("A", String.valueOf(A)).replace("B", String.valueOf(B)).replace("X", String.valueOf(X)).replace("Y", String.valueOf(Y)));
Matcher matcher = pattern.matcher(number);
if (matcher.find()) {
return true;
}
}
}
}
return false;
}
Question: Does anyone know or could suggest some better and faster solution?
I replaced Regex with custom matcher and 200k numbers are now processed during 5 seconds instead of 40 minutes!
public Set<String> performCollect() {
for (String number : numbers) {
if (isNumberMatches(number)) {
result.add(number);
}
}
return result;
}
protected boolean isNumberMatches(String number) {
NumberMatcher nm = new NumberMatcher(number, offset);
for (NumberPattern pattern : patterns) {
if (nm.processMatch(pattern)) {
return true;
}
}
return false;
}
...
public class NumberPattern {
private char[] maskChars;
private Integer weight;
public NumberPattern(String mask, Integer weight) {
maskChars = mask.toCharArray();
this.weight = weight;
}
public char[] getMaskChars() {
return maskChars;
}
public void setMaskChars(char[] maskChars) {
this.maskChars = maskChars;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
}
...
public class NumberMatcher {
private char[] numberChars;
private int uniqueChars = 0;
public NumberMatcher(String number, int offset) {
numberChars = number.toCharArray();
List<Character> chars = new ArrayList<>();
for (Character ch : number.substring(offset).toCharArray()) {
if (!chars.contains(ch)) {
uniqueChars++;
chars.add(ch);
}
}
}
public boolean processMatch(NumberPattern pattern) {
if (pattern.getWeight() < uniqueChars) {
return false;
}
Character X = null;
Character Y = null;
Character Z = null;
Character A = null;
Character B = null;
Character C = null;
Character D = null;
final char[] patternChars = pattern.getMaskChars();
int patternIndex = patternChars.length;
int numberIndex = numberChars.length;
while (patternIndex > 0) {
patternIndex--;
numberIndex--;
char numberChar = numberChars[numberIndex];
char patternChar = patternChars[patternIndex];
switch (patternChar) {
case 'A':
if (A == null) {
A = numberChar;
B = (char) (A + 1);
C = (char) (B + 1);
D = (char) (C + 1);
} else if (!A.equals(numberChar)) {
return false;
}
break;
case 'B':
if (B == null) {
B = numberChar;
A = (char) (B - 1);
C = (char) (B + 1);
D = (char) (C + 1);
} else if (!B.equals(numberChar)) {
return false;
}
break;
case 'C':
if (C == null) {
C = numberChar;
B = (char) (C - 1);
A = (char) (B - 1);
D = (char) (C + 1);
} else if (!C.equals(numberChar)) {
return false;
}
break;
case 'D':
if (D == null) {
D = numberChar;
C = (char) (D - 1);
B = (char) (C - 1);
A = (char) (B - 1);
} else if (!D.equals(numberChar)) {
return false;
}
break;
case 'X':
if (X == null) {
X = numberChar;
} else if (!X.equals(numberChar)) {
return false;
}
break;
case 'Y':
if (Y == null) {
Y = numberChar;
} else if (!Y.equals(numberChar)) {
return false;
}
break;
case 'Z':
if (Z == null) {
Z = numberChar;
} else if (!Z.equals(numberChar)) {
return false;
}
break;
case '.':
break;
case '0':
if (numberChar != '0') {
return false;
}
break;
}
}
return true;
}
}
I'm a bit new to java, I'm having one error with my Java program that I can't seem to fix, very easy solution I just can't see it haha. How can I fix this? I tried a few things but it adds more errors on top of each other. Thank you all!
import java.io.*;
import java.util.*;
class Node {
public char ch;
public Node leftChild;
public Node rightChild;
Node(char c) {
ch = c;
}
public void displayNode() {
System.out.print(ch);
}
}
class Tree {
public Node root;
public Tree(Node nd) {
root = nd;
}
public void traverse(int traverseType) {
switch (traverseType) {
case 1:
System.out.print(" \n Preorder traversal : ");
preOrder(root);
break;
case 2:
System.out.print(" \n Inorder traversal : ");
inOrder(root);
break;
case 3:
System.out.print(" \n Postorder traversal : ");
postOrder(root);
break;
}
System.out.println();
}
private void preOrder(Node localRoot) {
if (localRoot != null) {
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
}
}
private void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
}
}
public void displayTree() {
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(" ...................................................... ");
while (isRowEmpty == false) {
Stack localStack = new Stack();
isRowEmpty = true;
for (int j = 0; j < nBlanks; j++)
System.out.print(' ');
while (globalStack.isEmpty() == false) {
Node temp = (Node) globalStack.pop();
if (temp != null) {
temp.displayNode();
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if (temp.leftChild != null || temp.rightChild != null)
isRowEmpty = false;
} else {
System.out.print("-");
localStack.push(null);
localStack.push(null);
}
for (int j = 0; j < nBlanks * 2 - 1; j++)
System.out.print(' ');
}
System.out.println();
nBlanks / = 2;
while (localStack.isEmpty() == false)
globalStack.push(localStack.pop());
}
System.out.println(" ...................................................... ");
}
}
class BottomUp {
private String inString;
private int strlen;
private Tree[] treeArray;
private Tree aTree;
private int numNodes;
BottomUp(String s) {
inString = s;
strlen = inString.length();
treeArray = new Tree[100];
for (int j = 0; j < strlen; j++) {
char ch = inString.charAt(j);
Node aNode = new Node(ch);
treeArray[j] = new Tree(aNode);
}
}
public Tree getTree() {
return aTree;
}
public void balanced() {
numNodes = strlen;
while (numNodes > 1) {
int i = 0;
int j = 0;
Tree[] tempArray = new Tree[100];
for (j = 0; j < strlen - 1; j++) {
Tree tree1 = treeArray[j];
Tree tree2 = treeArray[j + 1];
Node aNode = new Node('+');
aTree = new Tree(aNode);
aTree.root.leftChild = tree1.root;
aTree.root.rightChild = tree2.root;
tempArray[i++] = aTree;
numNodes--;
j++;
}
if (strlen % 2 == 1) {
Tree tree1 = treeArray[j];
Node aNode = new Node('+');
aTree = new Tree(aNode);
aTree.root.leftChild = tree1.root;
tempArray[i++] = aTree;
}
treeArray = tempArray;
strlen = numNodes;
}
aTree = treeArray[0];
}
}
class BottomUpApp {
public static void main(String[] args) throws IOException {
BottomUp bup;
Tree theTree = null;
int value;
String str;
while (true) {
System.out.print(" Enter first letter of ");
System.out.print(" balanced , show , or traverse : ");
int choice = getChar();
switch (choice) {
case 'b':
System.out.print(" Enter string : ");
str = getString();
bup = new BottomUp(str);
bup.balanced();
theTree = bup.getTree();
break;
case 's':
theTree.displayTree();
break;
case 't':
System.out.print(" Enter type 1, 2 or 3 : ");
value = getInt();
theTree.traverse(value);
break;
default:
System.out.print(" Invalid entry \n ");
}
}
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
}
ERROR CODE
Node.java:112: error: illegal start of expression
nBlanks / = 2 ;
^
1 error
The Java operator /= must be typed without spaces in between, or else it will be parsed as 2 separate operators, / and =, which is a syntax error. Try
nBlanks /= 2 ;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
im work this assignment and keep getting Exception in thread
"main" java.lang.RuntimeException: Stack Underflow at Stack.pop(Postfix.java:74)
at Postfix.eval(Postfix.java:221)at Postfix.main(Postfix.java:112)
dont know why i look at the stack and write it correct , i cant see problem why it pop when (3*4)/5
import java.io.IOException;
class CharStack
{
private final int STACKSIZE= 80;
private int top;
private char[] items;
public CharStack(){
items = new char[STACKSIZE];
top =-1;
}
public boolean empty() {
if(top==-1){
return true;
}
return false;
}
public char pop() {
if(empty()){
throw new RuntimeException("Stack Underflow");
}
return items[top--];
}
public void push(char symb)
{
if(top == STACKSIZE -1) {
throw new RuntimeException("Stack Overflow");
}
items[++top] =symb;
}
public char peek() {
if(empty()){
throw new RuntimeException("Stack Underflow");
}
return items[top];
}
}
class Stack {
private final int STACKSIZE= 80;
private int top;
private double[] items;
public Stack(){
items = new double[STACKSIZE];
top =-1;
}
public void push(double x)
{
if(top == STACKSIZE -1) {
throw new RuntimeException("Stack Overflow");
}
items[++top] =x;
}
public double pop(){
if(empty()){
System.out.print(top);
throw new RuntimeException("Stack Underflow");
}
return items[top--];
}
public double peek() {
if(empty()){
throw new RuntimeException("Stack Underflow");
}
return items[top];
}
boolean empty()
{
if(top==-1){
return true;
}
return false;
}
}
public class Postfix {
public final static int MAXCOLS = 80;
public static void main(String[] args) throws IOException {
String infix, pfix;
System.out.println("Enter a infix String: ");
infix = readString().trim();
System.out.println("The original infix expr is: " + infix);
pfix = postfix(infix);
System.out.println("The Postfix expr is: " + pfix);
System.out.println("The value is : " + eval(pfix));
} // end main
public static boolean isOperand(char x)
{
if(x == '+')
{
return false;
}
else if(x == '-')
{
return false;
}
else if (x == '*')
{
return false;
}
else if (x == '/')
{
return false;
}
else if ( x== '$')
{
return false;
}
return true;
}
public static int operPrecedence(char oper)
{
if(oper == '+'||oper == '-' )
{
return 1;
}
else if (oper == '*' || oper == '/')
{
return 2;
}
else if (oper == '$')
{
return 3;
}
return 0;
}
public static boolean precedence(char top, char symb)
{
if ((top != '('||top != ')')&&symb == '(')
{
return false;
}
if (top == '(' && (symb != '('||symb != ')') )
{
return false;
}
else if((top != '('||top != ')')&&symb ==')' )
{
return true;
}
int opcode1, opcode2;
opcode1 =operPrecedence(top) ;
opcode2 =operPrecedence(symb) ;
if(opcode1>=opcode2){
return true;
}
return false;
}
public static String readString() throws IOException {
char[] charArray = new char[80];
int position = 0;
char c;
while ((c = (char) System.in.read()) != '\n') {
charArray[position++] = c;
}
return String.copyValueOf(charArray, 0, position); // turns a character array into a string, starting between zero and position-1
}// end read string
public static double eval(String infix) {
char c;
int position;
double opnd1, opnd2, value;
Stack opndstk = new Stack();
for (position = 0; position < infix.length(); position++) {
c = infix.charAt(position);
if (Character.isDigit(c)) // operand-convert the character represent of
// the digit into double and push it into the
// stack
{
opndstk.push((double) Character.digit(c, 10));
} else {
// operator
opnd2 = opndstk.pop();
opnd1 = opndstk.pop();
value = oper(c, opnd1, opnd2);
opndstk.push(value);
} // else
} // end for
return opndstk.pop();
}// end eval
public static String postfix(String infix) {
int position, outpos = 0;
char symb;
char[] postr = new char[MAXCOLS];
CharStack opstk = new CharStack();
for (position = 0; position < infix.length(); position++) {
symb = infix.charAt(position);
if (isOperand(symb)) {
postr[outpos++] = symb;
} else {
while (!opstk.empty() && precedence(opstk.peek(), symb)) {
postr[outpos++] = opstk.pop();
} // end while
if (symb != ')') {
opstk.push(symb);
} else {
opstk.pop();
}
} // end else
} // end for
while (!opstk.empty()) {
postr[outpos++] = opstk.pop();
}
return String.copyValueOf(postr, 0, outpos);
}// end pos
public static double oper(char symb, double op1, double op2) {
double value = 0;
switch (symb) {
case '+':
value = op1 + op2;
break;
case '-':
value = op1 - op2;
break;
case '*':
value = op1 * op2;
break;
case '/':
value = op1 / op2;
break;
case '$':
value = Math.pow(op1, op2);
break;
default:
throw new RuntimeException("illegal operator: " + symb);
}// end switch
return value;
}// end oper
}
At least part of the problem you're having is your isOperand method. The characters ( and ) are not operands, however, when they are passed to this method, it would return true. For a quick test, I added the following lines to the end of the method:
else if (x == '(')
{
return true;
}
else if (x == ')')
{
return true;
}
And your example input, (3*4)/5) runs successfully. However, this breaks your postfix output, as it leaves the brackets out of the postfix version and instead prints 34*5/, which I am guessing you don't want.
Then, I looked at your eval method, which is where the problem is coming from, according to the error message I'm receiving:
Exception in thread "main" java.lang.RuntimeException: Stack Underflow
at Stack.pop(Postfix.java:74)
at Postfix.eval(Postfix.java:221)
at Postfix.main(Postfix.java:112)
Note the line Postfix.java:221, which indicates the line that called the method which created the error. If you output your character c right before that line is called, you'll notice that c is the ( character, which means your eval method is recognizing ( as an operator, and is attempting to pop two operands after it, causing your underflow.
All of this is fairly simple to determine with some System.out.println() calls, and looking at your error. I'll leave the actual fixing to you, but at least you've hopefully got a direction to head in now.
This question already has answers here:
How to convert a char array back to a string?
(14 answers)
Closed 9 years ago.
i am doing a porter stemmer.....the code gives me output in char array....but i need to convert that into string to proceed with futher work.....in the code i have given 2 words "looking" and "walks"....that is returned as look and walk(but in char array)...the output is printed in stem() function
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package file;
import java.util.Vector;
/**
*
* #author sky
*/
public class stemmer {
public static String line1;
private char[] b;
private int i, /* offset into b */
i_end, /* offset to end of stemmed word */
j, k;
private static final int INC = 50;
/* unit of size whereby b is increased */
public stemmer()
{
//b = new char[INC];
i = 0;
i_end = 0;
}
/**
* Add a character to the word being stemmed. When you are finished
* adding characters, you can call stem(void) to stem the word.
*/
public void add(char ch)
{
System.out.println("in add() function");
if (i == b.length)
{
char[] new_b = new char[i+INC];
for (int c = 0; c < i; c++)
new_b[c] = b[c];
b = new_b;
}
b[i++] = ch;
}
/** Adds wLen characters to the word being stemmed contained in a portion
* of a char[] array. This is like repeated calls of add(char ch), but
* faster.
*/
public void add(char[] w, int wLen)
{ if (i+wLen >= b.length)
{
char[] new_b = new char[i+wLen+INC];
for (int c = 0; c < i; c++)
new_b[c] = b[c];
b = new_b;
}
for (int c = 0; c < wLen; c++)
b[i++] = w[c];
}
public void addstring(String s1)
{
b=new char[s1.length()];
for(int k=0;k<s1.length();k++)
{
b[k] = s1.charAt(k);
System.out.println(b[k]);
}
i=s1.length();
}
/**
* After a word has been stemmed, it can be retrieved by toString(),
* or a reference to the internal buffer can be retrieved by getResultBuffer
* and getResultLength (which is generally more efficient.)
*/
public String toString() { return new String(b,0,i_end); }
/**
* Returns the length of the word resulting from the stemming process.
*/
public int getResultLength() { return i_end; }
/**
* Returns a reference to a character buffer containing the results of
* the stemming process. You also need to consult getResultLength()
* to determine the length of the result.
*/
public char[] getResultBuffer() { return b; }
/* cons(i) is true <=> b[i] is a consonant. */
private final boolean cons(int i)
{ switch (b[i])
{ case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
}
/* m() measures the number of consonant sequences between 0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
*/
private final int m()
{ int n = 0;
int i = 0;
while(true)
{ if (i > j) return n;
if (! cons(i)) break; i++;
}
i++;
while(true)
{ while(true)
{ if (i > j) return n;
if (cons(i)) break;
i++;
}
i++;
n++;
while(true)
{ if (i > j) return n;
if (! cons(i)) break;
i++;
}
i++;
}
}
/* vowelinstem() is true <=> 0,...j contains a vowel */
private final boolean vowelinstem()
{ int i; for (i = 0; i <= j; i++) if (! cons(i)) return true;
return false;
}
/* doublec(j) is true <=> j,(j-1) contain a double consonant. */
private final boolean doublec(int j)
{ if (j < 1) return false;
if (b[j] != b[j-1]) return false;
return cons(j);
}
/* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
*/
private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
}
private final boolean ends(String s)
{
int l = s.length();
int o = k-l+1;
if (o < 0)
return false;
for (int i = 0; i < l; i++)
if (b[o+i] != s.charAt(i))
return false;
j = k-l;
return true;
}
/* setto(s) sets (j+1),...k to the characters in the string s, readjusting
k. */
private final void setto(String s)
{ int l = s.length();
int o = j+1;
for (int i = 0; i < l; i++)
b[o+i] = s.charAt(i);
k = j+l;
}
/* r(s) is used further down. */
private final void r(String s) { if (m() > 0) setto(s); }
/* step1() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
*/
private final void step1()
{
if (b[k] == 's')
{ if (ends("sses")) k -= 2; else
if (ends("ies")) setto("i"); else
if (b[k-1] != 's') k--;
}
if (ends("eed")) { if (m() > 0) k--; } else
if ((ends("ed") || ends("ing")) && vowelinstem())
{ k = j;
if (ends("at")) setto("ate"); else
if (ends("bl")) setto("ble"); else
if (ends("iz")) setto("ize"); else
if (doublec(k))
{ k--;
{ int ch = b[k];
if (ch == 'l' || ch == 's' || ch == 'z') k++;
}
}
else if (m() == 1 && cvc(k)) setto("e");
}
}
/* step2() turns terminal y to i when there is another vowel in the stem. */
private final void step2() { if (ends("y") && vowelinstem()) b[k] = 'i'; }
/* step3() maps double suffices to single ones. so -ization ( = -ize plus
-ation) maps to -ize etc. note that the string before the suffix must give
m() > 0. */
private final void step3() { if (k == 0) return; /* For Bug 1 */ switch (b[k-1])
{
case 'a': if (ends("ational")) { r("ate"); break; }
if (ends("tional")) { r("tion"); break; }
break;
case 'c': if (ends("enci")) { r("ence"); break; }
if (ends("anci")) { r("ance"); break; }
break;
case 'e': if (ends("izer")) { r("ize"); break; }
break;
case 'l': if (ends("bli")) { r("ble"); break; }
if (ends("alli")) { r("al"); break; }
if (ends("entli")) { r("ent"); break; }
if (ends("eli")) { r("e"); break; }
if (ends("ousli")) { r("ous"); break; }
break;
case 'o': if (ends("ization")) { r("ize"); break; }
if (ends("ation")) { r("ate"); break; }
if (ends("ator")) { r("ate"); break; }
break;
case 's': if (ends("alism")) { r("al"); break; }
if (ends("iveness")) { r("ive"); break; }
if (ends("fulness")) { r("ful"); break; }
if (ends("ousness")) { r("ous"); break; }
break;
case 't': if (ends("aliti")) { r("al"); break; }
if (ends("iviti")) { r("ive"); break; }
if (ends("biliti")) { r("ble"); break; }
break;
case 'g': if (ends("logi")) { r("log"); break; }
} }
/* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */
private final void step4() { switch (b[k])
{
case 'e': if (ends("icate")) { r("ic"); break; }
if (ends("ative")) { r(""); break; }
if (ends("alize")) { r("al"); break; }
break;
case 'i': if (ends("iciti")) { r("ic"); break; }
break;
case 'l': if (ends("ical")) { r("ic"); break; }
if (ends("ful")) { r(""); break; }
break;
case 's': if (ends("ness")) { r(""); break; }
break;
} }
/* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */
private final void step5()
{ if (k == 0) return; /* for Bug 1 */ switch (b[k-1])
{ case 'a': if (ends("al")) break; return;
case 'c': if (ends("ance")) break;
if (ends("ence")) break; return;
case 'e': if (ends("er")) break; return;
case 'i': if (ends("ic")) break; return;
case 'l': if (ends("able")) break;
if (ends("ible")) break; return;
case 'n': if (ends("ant")) break;
if (ends("ement")) break;
if (ends("ment")) break;
/* element etc. not stripped before the m */
if (ends("ent")) break; return;
case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break;
/* j >= 0 fixes Bug 2 */
if (ends("ou")) break; return;
/* takes care of -ous */
case 's': if (ends("ism")) break; return;
case 't': if (ends("ate")) break;
if (ends("iti")) break; return;
case 'u': if (ends("ous")) break; return;
case 'v': if (ends("ive")) break; return;
case 'z': if (ends("ize")) break; return;
default: return;
}
if (m() > 1) k = j;
}
/* step6() removes a final -e if m() > 1. */
private final void step6()
{ j = k;
if (b[k] == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1)) k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1) k--;
}
/** Stem the word placed into the Stemmer buffer through calls to add().
* Returns true if the stemming process resulted in a word different
* from the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public void stem()
{
// step1();
// System.out.println("hello in stem");
// step2();
// step3();
// step4();
// step5();
// step6();
//
// i_end = k+1;
// i = 0;
System.out.println(i);
k = i - 1;
if (k > 1)
{
step1();
step2();
step3();
step4();
step5();
step6();
}
for(int c=0;c<=k;c++)
System.out.println(b[c]);
i_end = k+1; i = 0;
}
public static void main(String[] args)
{
stemmer s = new stemmer();
s.addstring("looking");
s.stem();
s.addstring("walks");
s.stem();
//System.out.println("Output " +s.b);
}
}
- Use Character class method toString();
Eg:
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
char c = 'a';
String s = Character.toString(c);
System.out.println(s);
}
}
- Now use this above explained method to convert all the character array items into String.
char[] data = new char[10];
String text = String.valueOf(data);
to convert a char[] to string use this way
String x=new String(char[])
example
char x[]={'a','m'};
String z=new String(x);
System.out.println(z);
output
am
char[] a = new char[10];
for(int i=0;i<10;i++)
{
a[i] = 's';
}
System.out.println(new String(a));
or
System.out.println(String.copyValueOf(a));