I'll admit, I've gone through quite a few (similar) questions, but I can't seem to comprehend the contextual usage in the following piece of code I wrote for an elementary SPOJ problem (http://www.spoj.com/problems/ONP/):
import java.io.*;
import java.util.Stack;
import java.util.Scanner;
public class onp1 {
public static String postfixString(String expression) {
// Stack <Character> valueStack = new Stack <Character>();
Stack <Character> operatorStack = new Stack <Character>();
String output = "";
char[] tokens = expression.toCharArray();
for(char c : tokens) {
if(c == '('){
continue;
}
else if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^') {
operatorStack.push(c);
continue;
}
else if(c == ')') {
output += operatorStack.pop();
continue;
}
else {
output += String.valueOf(c);
continue;
}
}
return output;
}
public static void main (String [] args)throws java.lang.Exception {
String inputString = "";
int n1;
Scanner in = new Scanner(System.in);
try
{
n1 = in.nextInt();
StringBuilder[] sb = new StringBuilder[n1];
for(int i = 0; i < n1; i++) {
sb[i] = new StringBuilder();
inputString = in.next();
sb[i].append(postfixString(inputString));
}
for(int i = 0; i < n1; i++) {
System.out.println(String.valueOf(sb[i]));
}
}
catch (Exception e) {
// System.out.println("");
System.out.println(e.getMessage());
// numberOfTestCases.next();
}
System.exit(0);
}
}
If I use nextLine() instead of next(), the SPOJ engine generates a 'Wrong Answer' response.
Also, there seems to be some issue while using a StringBuilder object instead of a String object in the postfixString function (I was using a StringBuilder object earlier; was returning a string using the 'toString()' method).
Please ignore the logical inconsistencies (I know there are a few). I've already ironed (most) of them out. What's driving me crazy are nextLine()
vs next()
and StringBuilder vs String issues.