Reputation: 37
I have a problem with where I am getting a IndexOutOfBoundsException on line 22 of my code below. The program's purpose is to act as an expression evaluator with the following order of precedence:
Operator| Description | Level | Associativity
--------+-------------+-------+---------------
& | Bitwise AND | 1 | left to right
^ | Bitwise XOR | 2 | left to right
| | Bitwise OR | 3 | left to right
If the program is given the input expression like "1 | 8 & 3" using the scanner class, then the program should parse this input and output the result as 1.
Sample output:
Enter the expression: 1 | 8 & 3
Result of the given expression: 1
Explanation:
The way the evaluation is done is:
8 & 3 = 1000 & 0011 = 0000 = 0
1 | 0 = 0001 | 0000 = 1
I have been strugging with getting the program to work properly. Below is my latest code:
import java.util.ArrayList;
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) throws Exception {
try {
ArrayList<String> inputarray = new ArrayList<String>();
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Enter an expression with single digit integers (example: \"1 | 8 & 3\"): ");
if(input.hasNextLine()) {
inputarray.add(input.nextLine());
}
int j = 1;
j = 1;
for(int i = 0; i < inputarray.size(); i++) {
if(inputarray.get(j) == "&") {
inputarray.add((j+1), Integer.toString(Integer.parseInt(inputarray.get(j-1)) & Integer.parseInt(inputarray.get(j+1))));
System.out.println(" Result of the given expression: " + inputarray);
inputarray.remove((j-1));
inputarray.remove((j));
}
if(j <= (inputarray.size() - 3)) {
j += 2;
}
else if(j == (inputarray.size() - 2)) {
break;
}
}
j = 1;
for(int i = 0; i < inputarray.size(); i++) {
if(inputarray.get(j) == "^") {
inputarray.remove(j);
inputarray.add(j, Integer.toString(Integer.parseInt(inputarray.get(j-1)) ^ Integer.parseInt(inputarray.get(j+1))));
inputarray.remove((j-1));
inputarray.remove((j+1));
}
if(j <= (inputarray.size() - 3)) {
j += 2;
}
else if(j == (inputarray.size() - 2)) {
break;
}
}
j = 1;
for(int i = 0; i < inputarray.size(); i++) {
if(inputarray.get(j) == "|") {
inputarray.remove(j);
inputarray.add(j, Integer.toString(Integer.parseInt(inputarray.get(j-1)) | Integer.parseInt(inputarray.get(j+1))));
inputarray.remove((j-1));
inputarray.remove((j+1));
}
if(j <= (inputarray.size() - 3)) {
j += 2;
}
else if(j == (inputarray.size() - 2)) {
break;
}
}
}
catch(Exception e) {
e.printStackTrace();
System.err.println("Invalid input entered, please try again");
}
finally {
System.out.println();
main(null);
}
}
}
Upvotes: 0
Views: 113
Reputation: 103155
There are several problems.
.equals()
rather than ==. This has been discussed many time on Stackoverflow.Upvotes: 1