infix to postfix converter, not outputting right answer - java

I got a school-project where I was given this information:
for i=1 to m
if c_i is an operand: Transfer c_i to output.
if c_i is a left parentheses: Push c_i to tmp.
if c_i is a right parentheses: Pop elements from tmp and transfer
them to output until a left-parentheses
is met. Pop left-parentheses.
if c_i is an operator: Let the top tmp element be t. Pop and
transfer elements from tmp to output
until:
p(t) < p(c_i) or
t is a left-parentheses or
tmp is empty.
Push c_i to tmp.
Transfer the remaining elements in tmp to output.
I have been doing exactly these steps, but my output only gets right som times. I guess that Im thinking wrong somewhere around the if statement with the operators. I've constantly been debugging for 2 days now, and I just cant find the solution.
I would be very pleased if someone would like to check my code. The operatorCheck function is made for solving this: "We use the subroutine p to specify the priorities of the operators:
p(+) = 0,
p(−) = 0, p(∗) = 1, p(/) = 1
. This means that addition and subtraction have
lower priority compared to multiplication and division."
Code: http://pastebin.com/TA7UGiGc
Thank you!

You're looping and removing the first letter from tmp without getting the next letter to compare with in the while loop, therefore you need to get a new character inside the while loop.
The substring is also removing the wrong characters from tmp, it should keep everything except the first letter and that's accomplished with tmp.substring(1, tmp.length())
I have fixed that block of code below:
else if (character == '+' || character == '-' || character == '*' || character == '/'){
while (true) {
char t = tmp.length() > 0 ? tmp.charAt(0): ' ';
if (operatorCheck(t) < operatorCheck(character) || t == '(' || tmp.length() < 0) {
break;
}
output += t;
tmp = tmp.substring(1, tmp.length());
}
tmp = character + tmp;
}

Marco, in your code, the line 42
while (tmp.length() > 0 && !(operatorCheck(t) > operatorCheck(character)) && t != '(')
you have to change > with <
In the algorithm, the exit conditions are
tmp.length()==0 || p(t) < p(c_i) || t=='('
Since it's a while you have to negate that
!(tmp.length()==0 || p(t) < p(c_i) || t=='(')
===
(tmp.length()>0 && p(t) >= p(c_i) && t!='(')
=== (to write it with ! as you did)
(tmp.length()>0 && !(p(t) < p(c_i)) && t!='(')
Besides this, Dante is right about using stacks. If you want to avoid the autoboxing problem you can make your own primitive stack class for char

Related

Condition to point out Error in line formatting not being met

I have a program which reads a file and enforces a certain format in every line. If a line has a format error, it prints a line below it indicating which error it was.
For each line, From column 1 to 13 and 77 to 80, no formatting rules are enforced, so I don't care about dots in these columns.
For the case of the dot character, every dot must not be preceded by white space, and it must be followed by white space.
I have a condition to check for this, and at a glance it seems right, but it's still not catching errors in dot formatting.
public static boolean checkLineFormatErrors(String line){
int errorCount;
if(line.contains(".")){
errorCount = 0;
char[] charArr = line.toCharArray();
boolean problemWithDot = false;
for(int i = 0; i < charArr.length;i++){
if(i < charArr.length - 1
&& i > 12 && i < 76
&& charArr[i] == '.' && (charArr[i-1] == ' ' || charArr[i+1] != ' ')){
problemWithDot = true;
break;
}
}
if(problemWithDot){
errorMessage = "One or more dots do not follow the line format for this file.";
errorCount++;
if(errorCount > 1){
System.out.println(errorMessage);
}
else{
System.out.println(line + errorMessage);
}
}
}
return problemWithDot
}
All of my other methods for catching errors in format for other symbols work, it's only the dot one that doesn't.
For example
00012 ENVIRONMENT DIVISION .
00013 DATA DIVISION.
00014 WORKING-STORAGE SECTION.
00015 77 NUMERO1 PIC 9(2) VALUE ZEROS .
Line 12 and 15 should have an error message below them, because their final dot is preceded by a space.
(If you're wondering "Hey isn't that last bit of code Cobol?? Why are you not adding a cobol tag?" Yes those last lines are cobol! This is not a cobol issue because the program for checking the errors is made in Java only. Cobol is only a way to test the file to enforce its rules.)
By fixing your loop, it works, the main problem being with
i < charArr.length - 1
when the dot is at the end
for(int i = 12; i < charArr.length && i < 76;i++)
{
if(charArr[i] == '.' && (charArr[i-1] == ' ' ||
charArr[Math.min(charArr.length -1, i+1)] != ' '))
{
problemWithDot = true;
break;
}
}
note
charArr[i+1] != ' ' is likely to cause problem so check that i + 1 does not exceed the array length.

How to define 00-90 when I have charAt each of it

What I need to do is write a program that makes the first character (which is charAt(0) )and the second character (which is charAt(1) ) to become a value that not exceeding 90 which is (0 ~ 90) , but I also have to define them as an independent digit , because my program will make it to invalid if it is other than a digit.
So for an example it will become invalid if I type in 91
and it will valid if I type in number between 0~90
but I have no idea how to do this...
if(Character.isDigit(loop1.charAt(0))&&
Character.isDigit(loop1.charAt(1)))
I have tried this ,but not working
if(Character.isDigit(loop1.charAt(0)) &&
Character.isDigit(loop1.charAt(1)) &&
((loop1 >= 0)&&(loop1 <= 90)))
also this one but this is not working( I have no idea what I'm doing)
if(Character.isDigit(loop1.charAt(0)) &&
(((int)loop1.charAt(0)) >= 0) && <=9
Character.isDigit(loop1.charAt(1)) &&
((int)loop1.charAt(1)) <= 9)
Please help me... thanks a million !
Assuming I understand your question, parse loop1 and test the values using a simple if check, like
int t = Integer.parseInt(loop1);
if (t < 0 || t > 90) {
System.out.println("Value outside accepted range.");
} else {
System.out.println("Value valid.");
}
If I am getting this right you want to convert the first two characters of a string into a number and check is that number bigger than 90. Also you want the digits to be stored in different variables(?). If so this code should do it:
int digit1 = loop1.charAt(0) - '0';
int digit2 = loop1.charAt(1) - '0';
int number = digit1 * 10 + digit2;
if ( number <= 90 && number >= 0 )
System.out.println("Input is good");
else
System.out.println("Input is bad");

java "&&" operator behaving very strange

I am trying to print a pattern through java. I am using for loop and a conditional statement but there is some problem with && operator. I am not getting why it is behaving strange with my code specially. Following is my code.
public class Test{
public static void main(String ar[]){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if((i!=0 && j!=0)){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
output
unknown#unknown-Lenovo-E40-80:~/Desktop/java_test$ javac Test.java
unknown#unknown-Lenovo-E40-80:~/Desktop/java_test$ java Test
****
****
****
****
above output is totally different to my expectation. line 1 is not printed why? i just wanted to skip (i=0 and j=0) location's element.
Let's see what happens:
For line 1 you get i = 0 and j = 0 to 4, thus you'll get 5 spaces (because i = 0 will always end up in the result being false).
For all other lines i is != 0 and j is still 0 to 4 so you get 1 space and 4 stars.
If you change the space you print to a underscore you'd get the following output:
_____
_****
_****
_****
_****
i just wanted to skip (i=0 and j=0) location's element
Currently you are skipping all elements that don't have any of their indices being 0 (i != 0 && j != 0 translates to "i is not 0 and j is not 0").
If you only want to skip that one element you need to either change the expression to if( i == 0 && j == 0) { skip } or if( !(i == 0 && j == 0) ) { do_whatever_you_need } where the second translates to "if not both i and j are 0" (note that this means that either one can be 0, only the combination of both satisfies the condition).
Line 1 is getting printed, but it is printed with spaces.
The reason is because you are checking (i != 0 && j != 0). In the first iteration of the outer loop i is 0, hence the control goes to the else block.
Boolean algebra says that !a && !b == !(a || b). You are trying to say that !a && !b == !(a && b).
Your test of
if((i!=0 && j!=0))
is equivalent to
if(!(i==0 || j == 0))
This is not what you want, according to your final statement: "I just wanted to skip (i=0 and j=0) location's element."
And so, you can alter your test in a few ways. The first is probably easiest - reverse the blocks. This has the fewest operations and is easiest to understand.
if (i==0 && j==0)
System.out.print(" ");
else
System.out.print("*");
Or, if you want to maintain the order, alter your if statement. To invert your requirement of (i==0 && j==0): !(a && b) == (!a || !b)
if( (i!=0) || (j!=0) )
System.out.print("*");
else
System.out.print(" ");
The first line prints whitespaces, as I added in the comment, because, at this point i == 0 and prints it 4 times, but the second, third, and others attempts will print at first because will be equals to zero j == 0 after that four *
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if((i!=0 && j!=0)){
System.out.print("*");
} else {
System.out.print(" "); //THIS IS PRINTING THE FIRST LINE
}
}
System.out.println();
}
In first line i=0 so in first iteration of i control goes to else part and in first row spaces are printed instead of asterisks. And on every iteration of i first index j=0. So again else part executes and in first column again spaces are printed instead of asterisks. And on all other places asterisks are printed.
public class Test{
public static void main(String ar[]){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if((i!=0 && j!=0)){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}

The operator < is undefined for the argument type(s) boolean, int

I am new to processing and I am having trouble with this. I keep getting an error message for the bolded part of the code below. Is my syntax wrong?
void block(int x, int y, int s, color tinto) {
fill(tinto);
for (int i = 0; i < 3; i++) {
triple(x, y+i*s, s, tinto);
}
if (0 < i < 3 && 6 < i < 9) { // HERE
tinto = 255;
}
else {
tinto = tinto - 200;
}
}
In Java, to check if a variable is in a range you have to divide the statement into two parts, like this:
if (0 < i && i < 3 && 6 < i && i < 9){
}
This specific code will never be true, however, because you're asking for it to be in two different ranges. Perhaps you meant to check for either range?
if (0 < i && i < 3 || 6 < i && i < 9){
}
Note the || or operator instead of the && and operator.
The syntax is not valid, and I think you're expression is wrong anyway. You say i has to be within a range AND within another. I think you mean to write that it could be between one OR the other.
Example of valid syntax: instead of 0 < i < 3, write i > 0 && i < 3.
Try this:
if ( (i > 0 && i < 3) || (i > 6 && i < 9) )
Note that the following (which is what you were trying to do apparently) will never be evaluated to true because it cannot be within both ranges.
if ( (i > 0 && i < 3) && (i > 6 && i < 9) ) // incorrect
This isn't valid java expression. Try:
if (0<i && i<3 && 6<i && i<9){
There are two different problems with this code snippet. First, you have defined the 'i' variable as in "int" inside of the for loop. This instance of 'i' is no longer defined once you exit that for loop -- so the if statement below does not refer to that instance. To overcome this, define 'i' before the for loop...
int i;
for ( i=0; i<3; I++ ) {
...
}
if ( i ...
which brings me to the second error. The syntax "0 < i < 3" is not correct. In c/c++ the operators are executed one at a time ... so in this case the first "<" operator will be evaluated as "0 < i" and the result will be a Boolean (which will always be 'true' in your particular code snippet). But the important point is that the result is a Boolean. Next the code will attempt to evaluate that result with the next part of the statement -- "true < 3", which just doesn't make any sense, and so that receives a compiler error.
In your code snippet, there is no exit to the for loop until the value of i reaches 3, so this second "if" statement is unneeded. But if you did want to test to see whether i was between 1 and 2 (inclusive), then you would have to break those up into individual tests...
if ( 0 < i && i < 3 ...
Lastly ... if the value of i is between 1 and 2 (inclusive), then it cannot also be between 7 and 8 (inclusive) .. therefore the if statement as you coded it will always be false even after we correct the syntax.

cannot enter into an if block - java

The program is suppose to check if a string is consecutive including string such as zab and 901234. I wrote and exception to each so I can skip over 90 or za if they appear. Unfortunately I can't seem to get into the if block of code... I'm not sure why. If someone can help me get into this 901 it would be much appreciated.
for (int i=0; i<s.length()-1; i++){
if (s.charAt(i) == 9 && s.charAt(i + 1) == 0) {
System.out.println("in");
}
}
Remember, integers get converted to characters through the ASCII table, so you want the characters '9' and '0'
Your original code was actually looking for the null (0) and backspace (9) characters. More info on the ASCII table here: ASCII Table
for (int i=0; i<s.length()-1; i++){
if (s.charAt(i) == '9' && s.charAt(i + 1) == '0') {
System.out.println("in");
}
}
You need to test for charachers:
if (s.charAt(i) == '9' && s.charAt(i + 1) == '0') {

Categories

Resources