Recursive way to parse a string - java

I have a string "{x{y}{a{b{c}{d}}}}"
And want to print out recursively.
x
-y
-a
--b
---c
---d
This is what I have so far -
private static void printPathInChild2(String path) {
if (path.length() == 0) {
return;
}
if (path.charAt(0) == '{') {
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == '{' && i != 0) {
String t1 = path.substring(0,i);
System.out.println(t1);
printPathInChild2(path.substring(i));
} else if (path.charAt(i) == '}') {
String t2 = path.substring(0, i+1);
System.out.println(t2);
printPathInChild2(path.substring(i+1));
}
}
}
}
Struggling with the termination logic

If you want to add '-' characters that depend on the depth of the nesting, you should pass a second argument to the recursive call, which keeps track of the prefix of '-' characters.
When you encounter a '{', you add a '-' to the prefix.
When you encounter a '}', you remove a '-' from the prefix.
When you encounter any other character, you print the prefix followed by that character.
private static void printPathInChild2(String path,String prefix) {
if (path.length() == 0) {
return;
}
if (path.charAt(0) == '{') {
printPathInChild2(path.substring(1),prefix + "-");
} else if (path.charAt(0) == '}') {
printPathInChild2(path.substring(1),prefix.substring(0,prefix.length()-1));
} else {
System.out.println (prefix.substring(1) + path.charAt(0));
printPathInChild2(path.substring(1),prefix);
}
}
When you call this method with:
printPathInChild2("{x{y}{a{b{c}{d}}}}","");
You get:
x
-y
-a
--b
---c
---d
(I see that in your expected output 'd' has 4 '-'s, but I think it's an error, since 'd' has the same nesting level as 'c', so it should have 3 '-'s).
The method can also be written as follows:
private static void printPathInChild2(String path,String prefix) {
if (path.length() == 0) {
return;
}
char c = path.charAt(0);
if (c == '{') {
prefix = prefix + '-';
} else if (c == '}') {
prefix = prefix.substring(0,prefix.length()-1);
} else {
System.out.println (prefix.substring(1) + c);
}
printPathInChild2(path.substring(1),prefix);
}

Related

How to separate recursive string by comma

I have recursive string that goes like this,
var1=[[1,2,3], [1,2,3]], var2=true, var3="hello", var4=(var1=[[1,2,3], [1,2,3]], var2=true, var3="hello")
I want to separate the string by commas and desired result is this,
var1=[[1,2,3], [1,2,3]]
var2=true
var3="hello"
var4=(var1=[[1,2,3], [1,2,3]], var2=true, var3="hello")
I have tried this regex, (([a-zA-Z0-9]*)=(.*),?\s?)*, to match the something like this, varx=(), but the complete string was matched.
I also tried to do this by traversing the string but was not able to separate strings like varx="...." because the quotes can contain anythings so there was no way to do this.
public static int fun2(int start_index, String str, int end_index) {
Stack<Character> charStack = new Stack<>();
charStack.add(str.charAt(start_index));
char opp = ' ';
if (str.charAt(start_index) == '(') {
opp = ')';
} else if (str.charAt(start_index) == '[') {
opp = ']';
} else if (str.charAt(start_index) == '[')
while (end_index < str.length() && !charStack.isEmpty()) {
if (str.charAt(end_index) == str.charAt(start_index)) {
charStack.add(str.charAt(start_index));
} else if (str.charAt(end_index) == opp) {
charStack.pop();
}
end_index++;
}
if (charStack.isEmpty()) {
System.out.println("correct");
System.out.println(str.substring(start_index, end_index));
}
return end_index;
// throw error
}
public static void fun(String str) {
int start = 0;
int end = -1;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '=') {
System.out.println("key = " + str.substring(start, end + 1));
start = i + 1;
end = start + 1;
if (str.charAt(start) == '[' || str.charAt(start) == '(' || str.charAt(i) == '"') {
System.out.println("value = ");
end = fun2(start, str, end);
start = end;
i = start;
}
} else if (str.charAt(i) == ',' || str.charAt(i) == ' ') {
start++;
end++;
} else {
end++;
}
}
}
Can anyone suggest any regex or piece of code that will do this for me. Thanks in advance.
To get the matches in the example data, you could match the key part without matching an equals sign.
For the value you can either match from an opening till closing parenthesis, or match until the next key part or end of string.
Note that this pattern does not takes any recursion from the parenthesis or square brackets into account. It depends on matching the parenthesis or using the comma as a separator.
[^\s=,]+=(?:\([^()]*\)|.+?)(?=,\s*[^\s=,]+=|$)
Regex demo
In Java with the doubled backslashes
String regex = "[^\\s=,]+=(?:\\([^()]*\\)|.+?)(?=,\\s*[^\\s=,]+=|$)";

How to use variables in stack?

I'm trying to write a calc program that finds the infix. In addition the user will input numbers for the x variable and the program will solve it. My program works but it only solves it the first time. The following times it gives the same answer as the first time.
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
class Stack {
char a[] = new char[100];
int top = -1;
void push(char c) {
try {
a[++top] = c;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Stack full , no room to push , size=100");
System.exit(0);
}
}
char pop() {
return a[top--];
}
boolean isEmpty() {
return (top == -1) ? true : false;
}
char peek() {
return a[top];
}
}
public class intopost {
static Stack operators = new Stack();
public static void main(String argv[]) throws IOException {
String infix;
// create an input stream object
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
// get input from user
System.out.print("\nEnter the algebraic expression in infix: ");
infix = keyboard.readLine();
String postFx = toPostfix(infix);
// output as postfix
System.out.println("The expression in postfix is:" + postFx);
if (postFx.contains("x")) {
String line = "";
do {
System.out.println("Enter value of X : ");
line = keyboard.readLine();
if (!"q".equalsIgnoreCase(line)) {
postFx = postFx.replaceAll("x", line);
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
}
} while (!line.equals("q"));
} else {
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
}
}
private static String toPostfix(String infix)
// converts an infix expression to postfix
{
char symbol;
String postfix = "";
for (int i = 0; i < infix.length(); ++i)
// while there is input to be read
{
symbol = infix.charAt(i);
// if it's an operand, add it to the string
if (symbol != ' ') {
if (Character.isLetter(symbol) || Character.isDigit(symbol))
postfix = postfix + " " + symbol;
else if (symbol == '(')
// push (
{
operators.push(symbol);
} else if (symbol == ')')
// push everything back to (
{
while (operators.peek() != '(') {
postfix = postfix + " " + operators.pop();
}
operators.pop(); // remove '('
} else
// print operators occurring before it that have greater
// precedence
{
while (!operators.isEmpty() && !(operators.peek() == '(')
&& prec(symbol) <= prec(operators.peek()))
postfix = postfix + " " + operators.pop();
operators.push(symbol);
}
}
}
while (!operators.isEmpty())
postfix = postfix + " " + operators.pop();
return postfix.trim();
}
static int prec(char x) {
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/' || x == '%')
return 2;
return 0;
}
}
class EvaluateString {
public static int evaluate(String expression) {
char[] tokens = expression.toCharArray();
// Stack for numbers: 'values'
LinkedList<Integer> values = new LinkedList<Integer>();
// Stack for Operators: 'ops'
LinkedList<Character> ops = new LinkedList<Character>();
for (int i = 0; i < tokens.length; i++) {
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
continue;
// Current token is a number, push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9') {
StringBuffer sbuf = new StringBuffer();
// There may be more than one digits in number
while (i < tokens.length && tokens[i] >= '0'
&& tokens[i] <= '9')
sbuf.append(tokens[i++]);
values.push(Integer.parseInt(sbuf.toString()));
}
// Current token is an opening brace, push it to 'ops'
else if (tokens[i] == '(')
ops.push(tokens[i]);
// Closing brace encountered, solve entire brace
else if (tokens[i] == ')') {
while (ops.peek() != '(')
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
ops.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*'
|| tokens[i] == '/') {
// While top of 'ops' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'ops'
// to top two elements in values stack
while (!ops.isEmpty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
// Entire expression has been parsed at this point, apply remaining
// ops to remaining values
while (!ops.isEmpty())
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Top of 'values' contains result, return it
return values.pop();
}
// Returns true if 'op2' has higher or same precedence as 'op1',
// otherwise returns false.
public static boolean hasPrecedence(char op1, char op2) {
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
There is a mistake inside while loop in main method. See snippet below.
postFx = postFx.replaceAll("x", line);
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
Here postFx = postFx.replaceAll("x", line); you lost reference to postfix form that contains variable x. Subsequent calls of replaceAll doesn't have any effect. So expression with first entered value is evaluated.
You can easily fix it by replacing code above with
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx.replaceAll("x", line)));

Final return statement, ignore

Im working on a token iterator (valid tokens, "true, false, "true", "&", "!", "(", "false", "^", "true", ")".
The code is working, my question is about return values. I often run into this problem, I have return statements, but the final return statement throws off my result by duplicating the last return statement.
I think I know for sure the error lays within my placement of { and } and while i've learned they aren't necessary, since there's so many nested if's i feel they are necessary.
This seems to be a common problem to me and others ive worked with, does anyone have an idea of how to prevent this problem from happening? Thanks!
My code outputs:
line: [ ! BAD (true ^ false) % truelybad]
next token: [!]
next token: [(]
next token: [true]
next token: [^]
next token: [false]
next token: [)]
next token: [)]
and should output
next token: [!]
next token: [(]
next token: [true]
next token: [^]
next token: [false]
next token: [)]
public class TokenIter implements Iterator<String> {
ArrayList<String> token = new ArrayList<String>();
static int count = 0;
// input line to be tokenized
private String line;
// the next Token, null if no next Token
private String nextToken;
// implement
public TokenIter(String line) {
this.line = line;
}
#Override
// implement
public boolean hasNext() {
// System.out.println(count);
return count < line.length();
}
#Override
// implement
public String next() {
while (hasNext()) {
char c = line.charAt(count);
if (c == '!' || c == '!' || c == '^' || c == '(' || c == ')') {
token.add(Character.toString(c));
count++;
nextToken = Character.toString(c);
return nextToken;
} else if (c == 't' || c == 'T') {
count++;
c = line.charAt(count);
if (c == 'r') {
count++;
c = line.charAt(count);
}
if (c == 'u') {
count++;
c = line.charAt(count);
}
if (c == 'e') {
count++;
c = line.charAt(count);
}if (c == ' ' || c == '!' || c == '!' || c == '^' || c == '(' || c == ')'){
token.add("true");
nextToken = "true";
//count++;
return nextToken;
}
} else if (c == 'f' || c == 'F') {
count++;
c = line.charAt(count);
if (c == 'a') {
count++;
c = line.charAt(count);
}
if (c == 'l') {
count++;
c = line.charAt(count);
}
if (c == 's') {
count++;
c = line.charAt(count);
}
if (c == 'e') {
count++;
c = line.charAt(count);
}
if (c == ' ' || c == '!' || c == '!' || c == '^' || c == '(' || c == ')'){
token.add("false");
nextToken = "false";
// count++;
return nextToken;
}
} else if (c == ' ') {
count++;
} else {
count++;
}
}
return nextToken;
}
#Override
// provided, do not change
public void remove() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
// provided
public static void main(String[] args) {
String line;
// you can play with other inputs on the command line
if (args.length > 0)
line = args[0];
// or do the standard test
else
line = " ! BAD (true ^ false) % truelybad";
System.out.println("line: [" + line + "]");
TokenIter tokIt = new TokenIter(line);
while (tokIt.hasNext())
System.out.println("next token: [" + tokIt.next() + "]");
}
}
Problem with your code comes only when last digit is not a token.
Reason - You are checking hasNext() which is true it goes inside your code.You are not setting nextToken for this case so it uses your lask token and display it.
I updated your code to always return a value and check if value return is from token list then display otherwise ignore it.
public class test implements Iterator<String> {
static List<String> tokenList = Arrays.asList( "true", "&", "!", "(", "false", "^", "true", ")");
ArrayList<String> token = new ArrayList<String>();
static int count = 0;
// input line to be tokenized
private String line;
// the next Token, null if no next Token
private String nextToken;
// implement
public test(String line) {
this.line = line;
}
#Override
// implement
public boolean hasNext() {
// System.out.println(count);
return count < line.length();
}
#Override
// implement
public String next() {
while (hasNext()) {
char c = line.charAt(count);
if (c == '!' || c == '!' || c == '^' || c == '(' || c == ')') {
token.add(Character.toString(c));
count++;
nextToken = Character.toString(c);
return nextToken;
} else if (c == 't' || c == 'T') {
count++;
c = line.charAt(count);
if (c == 'r') {
count++;
c = line.charAt(count);
}
if (c == 'u') {
count++;
c = line.charAt(count);
}
if (c == 'e') {
count++;
c = line.charAt(count);
}if (c == ' ' || c == '!' || c == '!' || c == '^' || c == '(' || c == ')'){
token.add("true");
nextToken = "true";
//count++;
return nextToken;
}
} else if (c == 'f' || c == 'F') {
count++;
c = line.charAt(count);
if (c == 'a') {
count++;
c = line.charAt(count);
}
if (c == 'l') {
count++;
c = line.charAt(count);
}
if (c == 's') {
count++;
c = line.charAt(count);
}
if (c == 'e') {
count++;
c = line.charAt(count);
}
if (c == ' ' || c == '!' || c == '!' || c == '^' || c == '(' || c == ')'){
token.add("false");
nextToken = "false";
// count++;
return nextToken;
}
} else if (c == ' ') {
count++;
nextToken = null;
} else {
count++;
nextToken = null;
}
}
return nextToken;
}
#Override
// provided, do not change
public void remove() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
// provided
public static void main(String[] args) {
String line;
// you can play with other inputs on the command line
if (args.length > 0)
line = args[0];
// or do the standard test
else
line = " ! BAD (true ^ false) % truelybad ";
System.out.println("line: [" + line + "]");
test tokIt = new test(line);
while (tokIt.hasNext()) {
String s = tokIt.next();
if (s != null && tokenList.contains(s))
System.out.println("next token: [" + s + "]");
}
}
}
The underlying problem here is that your hasNext() method returns true not if there is another token in the String, but if it hasn't finished parsing the String yet.
So what happens is if you put in the String " ! ! true lotsofcrap ", then calling next() will return "!", then "!", then "true", then after that has been returned, there are no more tokens in the String, yet hasNext() still returns true.
What you might consider doing is having hasNext() parse through the string, but instead of returning the next String, return true only if it finds another token ahead of the current position. Keep in mind that in hasNext(), you do not want to directly increment count. Instead, make a local variable int something = count; at the beginning of hasNext() and use that. If you fix that, then the rest of your code SHOULD work just fine.

Custom Tokenizer, Iterator with quotes

Maybe some one can help?
How to modify this method next() that the next token can be: 'abc' text with the quotes.
Now if the text contains quote are throwed ExpressionException Unknown operator ''' at position...
#Override
public String next() {
StringBuilder token = new StringBuilder();
if (pos >= input.length()) {
return previousToken = null;
}
char ch = input.charAt(pos);
while (Character.isWhitespace(ch) && pos < input.length()) {
ch = input.charAt(++pos);
}
if (Character.isDigit(ch)) {
while ((Character.isDigit(ch) || ch == decimalSeparator)
&& (pos < input.length())) {
token.append(input.charAt(pos++));
ch = pos == input.length() ? 0 : input.charAt(pos);
}
} else if (ch == minusSign
&& Character.isDigit(peekNextChar())
&& ("(".equals(previousToken) || ",".equals(previousToken)
|| previousToken == null || operators
.containsKey(previousToken))) {
token.append(minusSign);
pos++;
token.append(next());
} else if (Character.isLetter(ch)) {
while ((Character.isLetter(ch) || Character.isDigit(ch) || (ch == '_')) && (pos < input.length())) {
token.append(input.charAt(pos++));
ch = pos == input.length() ? 0 : input.charAt(pos);
}
} else if (ch == '(' || ch == ')' || ch == ',') {
token.append(ch);
pos++;
//FIXME
else if (ch == '\''){
pos++;
String temp = "\'"+next()+"\'";
token.append(temp);
pos++;
}
//
} else {
while (!Character.isLetter(ch) && !Character.isDigit(ch)
&& !Character.isWhitespace(ch) && ch != '('
&& ch != ')' && ch != ',' && (pos < input.length())) {
token.append(input.charAt(pos));
pos++;
ch = pos == input.length() ? 0 : input.charAt(pos);
if (ch == minusSign) {
break;
}
}
if (!operators.containsKey(token.toString())) {
throw new ExpressionException("Unknown operator '" + token
+ "' at position " + (pos - token.length() + 1));
}
}
return previousToken = token.toString();
}
eval
public Object eval() {
Stack<Object> stack = new Stack<Object>();
for (String token : getRPN()) {
mylog.pl("Reverse polish notation TOKEN : " + token + " RPN size: " + getRPN().size() );
if (operators.containsKey(token)) {
Object v1 = stack.pop();
Object v2 = stack.pop();
stack.push(operators.get(token).eval(v2, v1));
} else if (variables.containsKey(token)) {
stack.push(variables.get(token).round(mc));
} else if (functions.containsKey(token.toUpperCase())) {
Function f = functions.get(token.toUpperCase());
ArrayList<Object> p = new ArrayList<Object>(f.getNumParams());
for (int i = 0; i < f.numParams; i++) {
p.add(0, stack.pop());
}
Object fResult = f.eval(p);
stack.push(fResult);
} else if (isDate(token)) {
Long date = null;
try {
date = SU.sdf.parse(token).getTime();
} catch (ParseException e) {/* IGNORE! */
}
stack.push(new BigDecimal(date, mc));
} else {
if (BusinessStrategy.PREFIX_X.equals(Character.toString(token.charAt(0)))) {
stack.push(token);
} else {
stack.push(new BigDecimal(token, mc));
}
}
}
return stack.pop();
}
Reverse notation
private List<String> getRPN() {
if (rpn == null) {
rpn = shuntingYard(this.expression);
}
return rpn;
}
Yard
private List<String> shuntingYard(String expression) {
List<String> outputQueue = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
Tokenizer tokenizer = new Tokenizer(expression);
String lastFunction = null;
while (tokenizer.hasNext()) {
String token = tokenizer.next();
if (isNumber(token)) {
outputQueue.add(token);
} else if (variables.containsKey(token)) {
outputQueue.add(token);
} else if (functions.containsKey(token.toUpperCase())) {
stack.push(token);
lastFunction = token;
} else if (Character.isLetter(token.charAt(0))) {
if ("\'".equals(Character.toString(token.charAt(0)))){
outputQueue.add(token);
} else {
stack.push(token);
}
} else if (",".equals(token)) {
while (!stack.isEmpty() && !"(".equals(stack.peek())) {
outputQueue.add(stack.pop());
}
if (stack.isEmpty()) {
throw new ExpressionException("Parse error for function '"
+ lastFunction + "'");
}
} else if (operators.containsKey(token)) {
Operator o1 = operators.get(token);
String token2 = stack.isEmpty() ? null : stack.peek();
while (operators.containsKey(token2)
&& ((o1.isLeftAssoc() && o1.getPrecedence() <= operators
.get(token2).getPrecedence()) || (o1
.getPrecedence() < operators.get(token2)
.getPrecedence()))) {
outputQueue.add(stack.pop());
token2 = stack.isEmpty() ? null : stack.peek();
}
stack.push(token);
} else if ("(".equals(token)) {
stack.push(token);
} else if (")".equals(token)) {
while (!stack.isEmpty() && !"(".equals(stack.peek())) {
outputQueue.add(stack.pop());
}
if (stack.isEmpty()) {
throw new RuntimeException("Mismatched parentheses");
}
stack.pop();
if (!stack.isEmpty()
&& functions.containsKey(stack.peek().toUpperCase())) {
outputQueue.add(stack.pop());
}
}
}
while (!stack.isEmpty()) {
String element = stack.pop();
if ("(".equals(element) || ")".equals(element)) {
throw new RuntimeException("Mismatched parentheses");
}
if (!operators.containsKey(element)) {
throw new RuntimeException("Unknown operator or function: "
+ element);
}
outputQueue.add(element);
}
return outputQueue;
}
Error
*java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at java.util.Stack.pop(Unknown Source)
at com.business.Expression.eval(Expression.java:1033)*
It is in eval method Object v1 = stack.pop(); line.
Thanks !
In method next you have recursive calls in two places:
after seeing a minus sign
after recognizing an apostrope
The first situation will construct tokens where a minus is followed by a digit (i.e., an unsigend number follows) - OK. (Although, not having a sign but an unary minus operator deserves some consideration.)
The second scenario means trouble. After advancing past the initial apostrophe, another next-result is expected, as if string literals would only contain one number or one identifier or a single operator. Anyway, the next() executes, let's say it returns a number: then an apostroph is added to the token, but there's no effort to check whether there is a closing apostrophe nor to skip that.
else if (ch == '\''){
token.append( '\'' );
pos++;
while( pos < input.length() &&
(ch = input.charAt(pos++)) != '\'' ){
token.append( ch );
}
token.append( '\'' );
This doesn't permit an apostrophe to be a character within the string and it does not diagnose an unterminated string. But this can be added rather easily.

String equation error checker not working

I have a method that checks to see if an equation written is correct.
This method check for:
Multiple Parentheses
Excess operators
Double Digits
q's
and any character in a string that is not and of these:
.
private static final String operators = "-+/*%_";
private static final String operands = "0123456789x";
It was working fine, but then I added in modular to the operators and now whenever my code reaches the part in the method that checks to the left and the right of an operand to see if it is neither the end of the string or the beginning I get an error saying
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
My method and all it's additional methods.
private static final String operators = "-+/*%_";
private static final String operands = "0123456789x";
public Boolean errorChecker(String infixExpr)
{
char[] chars = infixExpr.toCharArray();
StringBuilder out = new StringBuilder();
for (int i = 0; i<chars.length; i++)
{
System.out.print(infixExpr.charAt(i));
if (isOperator(infixExpr.charAt(i)))
{
if (i == 0 || i == infixExpr.length())
{
out.append(infixExpr.charAt(i));
}
else if (isOperator(infixExpr.charAt(i + 1)) && isOperator(infixExpr.charAt(i - 1)))
{
System.out.println("To many Operators.");
return false;
}
else if (isOperator(infixExpr.charAt(i + 1)))
{
if (infixExpr.charAt(i) != '-' || infixExpr.charAt(i + 1) != '-')
{
System.out.println("To many Operators.");
return false;
}
}
else if (isOperator(infixExpr.charAt(i - 1)))
{
if (infixExpr.charAt(i) != '-' || infixExpr.charAt(i - 1) != '-')
{
System.out.println("To many Operators.");
return false;
}
}
}
else if (isOperand(infixExpr.charAt(i)))
{
if (i == 0 || i == infixExpr.length())
{
out.append(infixExpr.charAt(i));
}//THE LINE RIGHT BELOW THIS COMMENT THROWS THE ERROR!!!!!
else if (isOperand(infixExpr.charAt(i + 1)) || isOperand(infixExpr.charAt(i - 1)))
{
System.out.println("Double digits and Postfix form are not accepted.");
return false;
}
}
else if (infixExpr.charAt(i) == 'q')
{
System.out.println("Your meow is now false. Good-bye.");
System.exit(1);
}
else if(infixExpr.charAt(i) == '(' || infixExpr.charAt(i) == ')')
{
int p1 = 0;
int p2 = 0;
for (int p = 0; p<chars.length; p++)
{
if(infixExpr.charAt(p) == '(')
{
p1++;
}
if(infixExpr.charAt(p) == ')')
{
p2++;
}
}
if(p1 != p2)
{
System.out.println("To many parentheses.");
return false;
}
}
else
{
System.out.println("You have entered an invalid character.");
return false;
}
out.append(infixExpr.charAt(i));
}
return true;
}
private boolean isOperator(char val)
{
return operators.indexOf(val) >= 0;
}
private boolean isOperand(char val)
{
return operands.indexOf(val) >= 0;
}
My main portion that runs the method:
Boolean meow = true;
while(meow)
{
System.out.print("Enter infix expression: ");
infixExpr = scan.next();//THE LINE RIGHT BELOW THIS COMMENT THROWS THE ERROR!!!!!
if(makePostfix.errorChecker(infixExpr) == true)
{
System.out.println("Converted expressions: "
+ makePostfix.convert2Postfix(infixExpr));
meow = false;
}
}
It was working fine before, but now it won't even pass 1+2 which was previously working and I changed NONE of that you see. What's wrong!?!?
What looks like what's happening is that you check for the character at index (i + 1) several times in your code. Lets say you input a string with a length of five characters. The program goes through and reaches the line:
else if (isOperator(infixExpr.charAt(i + 1)) && isOperator(infixExpr.charAt(i - 1)))
If i == 4, this will cause the code:
infixExpr.charAt(i + 1)
to throw an index error.
In essance, you're checking for a character at index five (the sixth character) in a string with a maximum index index of four which is five characters in length. Also, your checking for
if(i==0 || i == infixExpr.length)
won't work as is. Maybe check for (i==infixExpr.length-1).

Categories