I'm trying to convert infix to postfix expressions in Java, but somehow it's not reading it in correctly or there might be something wrong with my queue implementation. I tried debugging but I can't see where I went wrong.
Inputs:
2 + 3
4 + 5+6
(7+8) * 9
Output:
2+
4+5
78
Correct outputs would be:
23+
45+6+
78+9*
This is my code:
public int Prior (char c) {
if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return 0;
}
public String convertIn2Post() throws StackException, QueueException{
infix = infix.trim();
for(int i = 0; i < infix.length(); i++) {
if(Character.isDigit(infix.charAt(i))) {
expQueue.enqueue(infix.charAt(i) + "");
}
if (infix.charAt(i) == '(') {
opStack.push(infix.charAt(i) + "");
}
if (infix.charAt(i) == ')') {
while(opStack.peek().equals("(") != true) {
expQueue.enqueue(opStack.pop());
}
opStack.pop();
}
if ( infix.charAt(i) == '+' ||
infix.charAt(i) == '-' ||
infix.charAt(i) == '/' ||
infix.charAt(i) == '*' ) {
if(opStack.isEmpty()){
opStack.push(infix.charAt(i) + "");
}
while(Prior(infix.charAt(i)) <= Prior(opStack.peek().charAt(0))){
expQueue.enqueue(opStack.pop());
if(opStack.isEmpty()){
break;
}
}
}
}
while(!opStack.isEmpty()){
expQueue.enqueue(opStack.pop());
}
for(int y = 0; y < expQueue.size(); y++){
postfix += expQueue.dequeue();
}
return "postfix:: " + postfix;
}
First off, one simple bug in the program is the loop that will dequeue everything. Notice, that each time the loop is run, it checks that
y < expQueue.size()
but, everytime an element is dequeued from the queue, this value is decreasing. So, if the size starts at 6, the program will run for y = 0, size = 6, y = 1, size = 5, y = 2 size = 4, y = 3 size = 3 and that is where it stops. So change this to a while loop:
while(!expQueue.isEmpty())
Next, the algorithm for converting infix to postfix says that if the opstack is empty, to push the operator, which is correct in the code. Then it says that if it is not empty, if the one just found is of higher priority than the one on top of the stack, to add that one to the top of the stack, otherwise pop the top and add the new operator to the stack; this can be done as follows:
if(opStack.isEmpty()){
opStack.push(infix.charAt(i) + "");
}
else
{
String peek = opStack.peek();
if(Prior(peek.charAt(0)) >= Prior(infix.charAt(i)))
{
expQueue.add(opStack.pop());
opStack.push(infix.charAt(i) + "");
}
else
{
opStack.push(infix.charAt(i) + "");
}
}
Related
I had this program where I had to take the two numbers and a symbol from an expression like:
**111*369**
But here:
for(i=0; i<t; i++) {
while(w) {
if(ar1[i].charAt(j)=='+' || ar1[i].charAt(j)=='-' || ar1[i].charAt(j)=='*' || ar1[i].charAt(j)=='/') {
w = false;
}
else {
k = ar1[i].charAt(j);
a = a*10 + (long)(k-48);
}
}
The program never goes to inside the if-statement. It gets into an infinite loop.
So why isn't it checking the symbols?
Here's the link for the complete program with the output: My Program
Your while loop always checks the same character in the condition, since you never increment j. Therefore, if that character is not an operator, the loop will never terminate.
You should increment j in each iteration, and take care not to increment j past the last index ar1[i] :
while(w && j < ar1[i].length) {
if(ar1[i].charAt(j)=='+' || ar1[i].charAt(j)=='-' || ar1[i].charAt(j)=='*' || ar1[i].charAt(j)=='/') {
w=false;
}
else {
k=ar1[i].charAt(j);
a=a*10+ (long)(k-48);
}
j++;
}
Look at your while statement:
while (w) {
if (ar1[i].charAt(j) == '+' || ar1[i].charAt(j) == '-' || ar1[i].charAt(j) == '*' || ar1[i].charAt(j) == '/') {
w = false;
} else {
k = ar1[i].charAt(j);
a = a * 10 + (long)(k - 48);
}
}
If the if condition is false, you go to the else block. The else block does nothing to change w and does nothing to change the things being tested by the if, so the loop continues forever.
i need help on a verification on a string
I have to write a method that verify if 2 parameters of the method have the same length and if the second one have numbers between 0 and 3.
Let's see what i wrote :
public static boolean coupEstValide( String combinaison, String coup ){
boolean res = true;
if(combinaison.length() == coup.length()){
int i = 0;
while(i < coup.length() && res == true){
char t = coup.charAt(i);
if(t <= 0 && t >= 3)
res = false;
i++;
}
}
return res;
in my opinion, this should work... But if i do this :
coupEstValide("555", "104");
it should tell me false but it it's telling me it's true.
Do you guys see what's wrong ?
Thanks
When you compare Character with an integer actually ASCII value of that character gets compared with that integer. That's why you keep getting true.
So as already suggested in the comments you should compare it either as if(t >= '0' && t <= '3') or use any Utility method of java.lang such as Character.compare(char lhs, char rhs).
Hope this would be helpful.
Enjoy!
A few of problems in your code:
If the lengths are different, you are still returning true!
Strings are composed of characters. Their value is their character code. 0 to 3 are 48 to 51, respectively. Use character constants not integer constants: if (t == '0') will check if t is the character "0".
Your logic for the comparison isn't right anyways. Using your original (incorrect) example with integers, and correcting from <= and >= based on your comments: if (t < 0 && t > 3) will never be true, t cannot simultaneously be less than 0 and greater than 3. I'll leave the correct boolean statement as an exercise to the reader (hint: or).
Alright, i fixed the problem.
So as you said, i should've use
if(t < '0' || t > '3')
And to fix the problem of the time both are not the same size, i added an else.
So the full code is that :
public static boolean coupEstValide( String combinaison, String coup ){
boolean res = true;
if(combinaison.length() == coup.length()){
int i = 0;
while(i < coup.length() && res == true){
char t = coup.charAt(i);
if(t < '0' || t > '3')
res = false;
i++;
}
}
else
res = false;
return res;
}
Thanks for your help guys !
This would never true. A number can not be less and equal to zero and at the same time greater and equal to 3.
if(t <= 0 && t >= 3)
If you want to evaluate whether a character is between 0 and 3 you must use this:
if(t >= '0' && t <= '3')
Now if you want to evaluate if the character is not between 0 and 3 then try this:
if (t <'0' || t> '3')
String coup = "053";
boolean res = true;
int i = 0;
while (i < coup.length() && res == true) {
System.out.println(coup.length());
int t = Integer.parseInt(coup.charAt(i) + "");
System.out.println("T is " + t);
if (t <= 0 || t >= 3) {
res = false;
i++;
}
System.out.println("Value i " + i);
System.out.println("Value of the Res at last" + res);
}
may be this could be helpful try to convert it to the integer
according to your code
String coup = "053";
boolean res = true;
int i = 1;
while (i < coup.length() && res == true) {
System.out.println(coup.length());
//int t = Integer.parseInt(coup.charAt(i) + "");
char t = coup.charAt(i);
System.out.println("T is " + t);
if (t <= 0 || t >= 3) {
res = false;
i++;
}
System.out.println("Value i " + i);
System.out.println("Value of the Res at last" + res);
}
Code is supposed to do this: Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
The problem: Ran across Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 11 (line number:10)
public int countCode(String str){
int a = 0; // counter goes thru string
int b = str.length()-1;
int counter = 0; //counts code;
if(str.length() < 4) return 0;
else{
while (a <=b){
if(str.charAt(a) == 'c'){
if(str.charAt(a+1) == 'o'){
if(str.charAt(a+3) == 'e'){
counter++;
a= a+3;
} // checks e
else a++;
} // checks o
else a++;
} // checks c
else a++;
}
return counter;
}
}
Here's what I tried to evaluate to get said exception:
countCode("xxcozeyycop") --> EXPECTED RESULT 1
countCode("cozcop") --> EXPECTED RESULT
Your loop goes from 0 to the length of the string (excluded). But inside the loop, you're doing
str.charAt(a+3)
Obviously, if a is length - 1, a + 3 is length + 2, and you're thus trying to access an element outside the bounds of the string.
Side note: you would understand your own code better if you indented it correctly.
Instead of
while (a <=b){
use
while (a <= b - 3){
Reason: Your end sign in the while is the condition that the start of the String "code" is inside the String. However, if a = b - 2, then a + 3 = b + 1 = (str.length() - 1 + 1) = str.length() which is just outside the String.
public int countCode(String str) {
int count = 0;
for(int i = 0; i < str.length()-3; i++)
if(str.substring(i, i+2).equals("co") && str.charAt(i+3) == 'e')
count++;
return count;
}
I am trying to print every second letter in the string but for some reason I only print the first second letter correctly but after that it keeps printing in a weird order. Here is my code:
out.print("Please enter a word: ");
String word = in.nextLine();
char[] c = word.toCharArray();
int x = 0;
while (x < c.length) {
if (c[x] % 2 != 0) {
out.print(word.charAt(x) + " ");
}
x++;
}
You should change this:
if (c[x] % 2 != 0) {
to
if (x % 2 != 0) {
This compares the index you are working with instead of comparing the character. x is the position of the character. c[x] is the character. You can read c[x] as "the value at position x in array c".
Why are you attempting to determine if the character (c[x]) is odd? You should be testing the index itself.
if (x % 2 != 0) {
You are calculating the character modulo 2 instead of the index modulo 2
By the way:
String word …
for(int ix=1; ix<word.length(); ix+=2)
out.print(word.charAt(ix) + " ");
makes it far simpler.
Problem area: You are checking value instead of index
while (x < c.length) {
if (c[x] % 2 != 0) {
out.print(word.charAt(x) + " ");
}
Convert it to: Checking index instead of value
while (x < c.length) {
if (x % 2 != 0) {
out.print(word.charAt(x) + " ");
}
I am tying to implement a depth first search algorithm in java to find the best way to move in a quadratic matrix. I am avoiding to create "unnecessary" objects, i.e object just to hold (X,Y) positions.
Am I forgetting something? I am running it with starting points of (0,0) and with objective of (4,5). What happens is an infinite loop.
int x = this.move_to_x;
int y = this.move_to_y;
Stack X = new Stack();
Stack Y = new Stack();
Stack visited_X = new Stack();
Stack visited_Y = new Stack();
X.push(this.current_x);
Y.push(this.current_y);
while(!X.empty()){
int tmp_x = (int)X.pop();
int tmp_y = (int)Y.pop();
if(tmp_x == x && tmp_y == y){
System.out.println("best way found!");
return;
}
//there is only 8 possible ways to go (the neighbors)
for(int a = -1; a < 2; a++){
for(int b = -1; b < 2; b++){
if(a == 0 && b == 0){
break;
}
if(visited_X.search(tmp_x + a) == -1 && visited_Y.search(tmp_y + b) == -1){
X.push(tmp_x + a);
Y.push(tmp_y + b);
visited_X.push(tmp_x + a);
visited_Y.push(tmp_y + b);
System.out.println("added x " + tmp_x + a + " y " + tmp_y + b);
}
}
}
}
I can see several problems:
1) In the following:
if(a == 0 && b == 0){
break;
}
you should be using continue rather than break.
2) The following:
if(visited_X.search(tmp_x + a) == -1 && visited_Y.search(tmp_y + b) == -1){
is incorrect: the (tmp_x, tmp_y) pair has to be present at the same index in visited_X/visited_Y.
3) You should add the starting position to visited_{X,Y}.
4) Algorithmically, I don't see any reason to think that your method would return the shortest path.
5) The reason your code ends up in (an almost) infinite loop is that you don't check for the matrix boundaries.