String Math Algorithm Gone Wrong JavaFX - java

As I was building my first JavaFX project, I noticed that the calculator engine that I had built was a little off. With that being said, I went over my code for about an hour now, trying to figure out what is wrong and I couldn't find anything that connects to this strange bug in my program.
The calculator engine:
public static String BasicEval(String str, String function) {
int indexOfOperation = str.indexOf(function);
int downBoundary = indexOfOperation - 1;
int upBoundary = indexOfOperation + 1;
int closestUp = str.length(), closestDown = 0;
for (int index = 0; index < str.length(); index++) { // Searching for the closest white space (between vals.) to determine what are the two vals.
if (Math.abs(indexOfOperation - index) == 1) {
continue;
} else if ((str.charAt(index) == ' ') && ((indexOfOperation - index) > closestDown)) {
closestDown = index; //Finds the closest blank space in order to differentiate between elements.
} else if ((str.charAt(index) == ' ') && (Math.abs(indexOfOperation + index) < closestUp)) {
closestUp = index; //Finds the closest black space in order to differentiate between elements.
}
}
while (str.substring(upBoundary,closestUp).contains("X") || (str.substring(upBoundary,closestUp).contains("-") || (str.substring(upBoundary,closestUp).contains("+") || (str.substring(upBoundary,closestUp).contains("/") || (str.substring(upBoundary,closestUp).contains("^")))))) {
closestUp--;
}
double firstValue = Double.valueOf(str.substring((closestDown + 1), downBoundary));
double secondValue = Double.valueOf(str.substring(upBoundary + 1, (closestUp-1)));
double OperationResult;
switch (function) {
case "^" : OperationResult = Math.pow(firstValue,secondValue); break;
case "X" : OperationResult = (firstValue * secondValue); break;
case "/" : OperationResult = (firstValue / secondValue); break;
case "+" : OperationResult = (firstValue + secondValue); break;
case "-" : OperationResult = firstValue - secondValue; break;
default: OperationResult = -999.12349876; //ERROR
}
str = strSort(str,firstValue,secondValue,OperationResult);
return str;
}
A little bit about the engine: the engine itself supposes to evaluate math expressions inside strings, so for example an input would be: " 3 + 4 " and the answer would be: 7.0 as a double. The way I hoped to achive this was by deviding the str into 4 smaller sections by the spaces between the terms and operation sign. The problem is: the math gets all wierd as you use bigger numbers. The number -999.123... stands for an error in my program.
The engine works just fine for simple calculations that use low numbers, but as you start to use bigger numbers things get messy. Sometimes it also produces errors like: "empty string", which I don't understand why ..
For more info about the project or the engine please comment.
-- Keep in mind that I'm looking for an answer that would apply to my algorithm, not to javaFX in general-- (though I'd love to learn new stuff)
Thanks !!
Examples of how things aren't as they should be:
enter image description here
enter image description here
I'll post more pictures in the comments.
strSort Method
public static String strSort(String str, double firstValue, double secondValue, double result) {
//Method that sorts between which vals are ints and which ones are doubles. --> returns them in their current form.
int firstValueIndex = 0;
int secondValueIndex = 0;
if (!intOrDoubleTest(firstValue) && firstValue == secondValue){ // Special category : indexOf doesn't work since the two vals. are the same --> giving off the same index.
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Double.toString(secondValue),firstValueIndex+1);
} else if (intOrDoubleTest(firstValue) && firstValue == secondValue) { // Special category : indexOf doesn't work since the two vals. are the same --> giving off the same index.
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)),firstValueIndex+1);
} else if (intOrDoubleTest(firstValue) && intOrDoubleTest(secondValue)) { // First, sorts out the two vals.
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)));
} else if (!intOrDoubleTest(firstValue) && intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)));
} else if (intOrDoubleTest(firstValue) && !intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Double.toString(secondValue));
} else if (!intOrDoubleTest(firstValue) && !intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Double.toString(secondValue));
}
String strToReplace = str.substring(firstValueIndex, secondValueIndex); // Computing the range that need to be replaced.
if (intOrDoubleTest(result)) {
int intResult = intValue(result);
str = str.replace(strToReplace,Integer.toString(intResult));
} else if (!intOrDoubleTest(result)) {
str = str.replace(strToReplace,Double.toString(result));
}
return str;
}
public static boolean intOrDoubleTest(double value) {
return (value % 1 == 0); // True = val is Int, False = val is Double.
}

Found the problem:
The problem was in the strToReplace.substring the strSort method. So naturally, I re-wrote the entire method in a much simpler, nicer way.
public static String strSort(String str, double firstValue, double secondValue, double result) {
//Method that sorts between which vals are ints and which ones are doubles. --> returns them in their current form.
int firstValueIndex;
int secondValueIndex;
if (intOrDoubleTest(firstValue)) {
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
} else {
firstValueIndex = str.indexOf(Double.toString(firstValue));
}
if (intOrDoubleTest(secondValue)) {
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)), firstValueIndex+1);
} else {
secondValueIndex = str.indexOf(Double.toString(secondValue), firstValueIndex+1);
}
int lengthOfSecondVal;
lengthOfSecondVal = (int)(Math.log10(secondValue)+1);
String strToReplace = str.substring(firstValueIndex, secondValueIndex+lengthOfSecondVal); // Computing the range that need to be replaced.
if (intOrDoubleTest(result)) {
int intResult = intValue(result);
str = str.replace(strToReplace,Integer.toString(intResult));
} else if (!intOrDoubleTest(result)) {
str = str.replace(strToReplace,Double.toString(result));
}
return str;
}
public static boolean intOrDoubleTest(double value) {
return (value % 1 == 0); // True = val is Int, False = val is Double.
}
Thank you to all of you that helped !!

Related

Need to encode repetitive pattern in String with * , such that * means "repeat from beginning"

Encoding format: introduce * to indicate "repeat from beginning". Example. Input-{a,b,a,b,c,a,b,a,b,c,d} can be written as {a , b, * ,c, * , d}. Output:5; E.g 2: ABCABCE, output- 5.
Here * means repeat from beginning. For example if given String is ABCABCABCABC , it will return ABC**, another example is if String is ABCABCABC, it will return ABC*ABC.
I have the below code but this code assumes that the string will contain the repetitive pattern only and no other characters, I want to modify it to check :
1. Which pattern is repeating
2. Ignore non repeating patterns
2. encode that pattern according to the problem statement
import java.util.Scanner;
public class Magicpotion {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string:");
String str = sc.nextLine();
int len = str.length();
if (len != 0) {
int lenby3 = len / 3;
int starcount = ( int).(Math.log(lenby3) / Math.log(2));
int leftstring = (lenby3 - (int) Math.pow(2, starcount));
int resultlen = (1 * 3) + starcount + (leftstring * 3);
System.out.println("ResultLength: " + resultlen);
System.out.print("ABC");
for (int i = 0; i < starcount; i++) {
System.out.print("*");
}
for (int i = 0; i < leftstring; i++) {
System.out.print("ABC");
}
} else
System.out.println("ResultLength: " + 0);
}
}
Here my assumption is that ABC will always be repeating pattern , hence I have divided the length by 3. I want to generalise it such that I find the repeating pattern which can be a AB or BC or ABCD and proceed accordingly.
This looks like homework. So instead of a full solution just some hints:
You can process the input string character by character and encode as you go. If you have at some point already read k characters and the next k characters are exactly the same, output a * and advance to position 2k.
Otherwise, output the next input character and advance position to k+1.
As mentioned by dyukha this algorithm does not always result in the shortest possible encoding. If this is required some more effort has to be put into the search.
This problem can be solved using dynamic programming.
Assume that you processed your stay at some position i. You want to understand what it the minimal length of encoding of str[0..i]. Let's call it ans[i]. You have two options:
Just add i-th character to the encoding. So the length is ans[i-1] + 1.
You may write *, when possible. In this case the length is ans[i / 2] + 1 or something like this.
The final length is in ans[n-1]. You can store how you obtained ans[i] to recover the encoding itself.
Checking whether you can write * can be optimized, using some hashing (to obtain O(n) solution instead of O(n^2)).
The difference with Henry's solution is that he always applies * when it's possible. It's not clear to me that it results into the minimal length (if I understood correctly, aaaaaa is a counterexample), so I'm giving a solution I'm sure about.
/**
* #author mohamed ali
* https://www.linkedin.com/in/oo0shaheen0oo/
*/
public class Magic_potion_encoding
{
private static int minimalSteps( String ingredients )
{
StringBuilder sb = new StringBuilder(ingredients);
for(int i =0;i<sb.length();i++)
{
char startChar = sb.charAt(i);
int walkingIndex1=i;
int startIndex2 =sb.toString().indexOf(startChar,i+1);
int walkingIndex2=startIndex2;
while(walkingIndex2 !=-1 && walkingIndex2<sb.length() && sb.charAt(walkingIndex1) == sb.charAt(walkingIndex2) )
{
if(walkingIndex1+1==startIndex2)
{
String subStringToBeEncoded = sb.substring(i,walkingIndex2+1);//substring the string found and the original "substring does not include the last index hence the +1
int matchStartIndex = sb.indexOf(subStringToBeEncoded,walkingIndex2+1);// look for first match for the whole string matched
int matchEndeIndex= matchStartIndex+subStringToBeEncoded.length();
int origStartIndex=i;
int origEndIndex = i+subStringToBeEncoded.length();
if (matchStartIndex!=-1 )
{
if(origEndIndex==matchStartIndex)
{
sb.replace(matchStartIndex,matchEndeIndex,"*");
}
else
{
while(matchStartIndex!=-1 && matchEndeIndex<sb.length() && sb.charAt(origEndIndex) == sb.charAt(matchEndeIndex) )
{
if(origEndIndex==matchStartIndex-1)// if the index of the 2 strings are right behind one another
{
sb.replace(matchStartIndex,matchEndeIndex+1,"*");
}
else
{
origEndIndex++;
matchEndeIndex++;
}
}
}
}
sb.replace(startIndex2,walkingIndex2+1,"*");
break;
}
walkingIndex1++;
walkingIndex2++;
}
}
System.out.println("orig= " + ingredients + " encoded = " + sb);
return sb.length();
}
public static void main( String[] args )
{
if ( minimalSteps("ABCABCE") == 5 &&
minimalSteps("ABCABCEA") == 6 &&
minimalSteps("abbbbabbbb") == 5 &&
minimalSteps("abcde") == 5 &&
minimalSteps("abcbcbcbcd") == 6 &&
minimalSteps("ababcababce") == 6 &&
minimalSteps("ababababxx") == 6 &&
minimalSteps("aabbccbbccaabbccbbcc") == 8)
{
System.out.println( "Pass" );
}
else
{
System.out.println( "Fail" );
}
}
}
Given that the repetitions are from the beginning, every such repeating substring will have the very first character of the given string. [Every repetition needs to be represented by a "star". (i.e ABCABCABC ans = ABC** ) . If all sequential repetitions are to be represented with one "star". (i.e ABCABCABC and = ABC* ), a slight modification to (2) will do the thing (i.e remove the if case where the just a star is added)]
Divide the given string to substrings based on the first character.
Eg. Given String = "ABABCABD"
Sub Strings = {"AB", "ABC", "AB", "ABD"}
Just traverse through the list of substrings and get the required result. I've used a map here, to make the search easy.
Just a rough write up.
SS = {"AB", "ABC", "AB", "ABD"};
result = SS[0];
Map<string, bool> map;
map.put(SS[0],true);
for (i = 1; i < SS.length; i++){
if (map.hasKey(SS[i])){
result += "*";
}
else {
res = nonRepeatingPart(SS[i], map);
result += "*" + res;
map.put(SS[i], true);
}
}
String nonRepeatingPart(str, map){
for (j = str.length-1; j >= 0; j--){
if (map.hasKey(str.subString(0, j))){
return str.subString(j, str.length-1);
}
}
return throwException("Wrong Input");
}
string getCompressed(string str){
string res;
res += str[0];
int i=1;
while(i<str.size()){
//check if current char is the first char in res
char curr = str[i];
if(res[0]==curr){
if(str.substr(0,i)==str.substr(i,i)){
res += '*';
i+=i; continue;
}else{
res += curr;
i++; continue;
}
}else {
res += curr;
i++; continue;
}
}
return res;
}
int main()
{
string s = "ABCABCABC";
string res = getCompressed(s);
cout<<res.size();
return 0;
}

Java parse int/long from binary literal string

Java wonderfully provides Long.decode to parse most int formats, but not binary:
Long.decode("11") => 11
Long.decode("011") => 9
Long.decode("0x11") => 17
Long.decode("0b11") => java.lang.NumberFormatException
Is there a method that will parse a string containing a binary literal for me?
P.S.
I understand if I wanted to extract the radix/value myself I could use the binary form of Long.parseLong, but ideally what I'm looking for would be a function that could parse "0b11" without any pre-processing.
There is no way in the standard Java API. However, I would take a look at Long.decode() code and adapt it:
public static Long decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Long result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
/// >>>> Add from here
else if (nm.startsWith("0b", index) || nm.startsWith("0B", index)) {
index += 2;
radix = 2;
}
/// <<<< to here
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Long.valueOf(nm.substring(index), radix);
result = negative ? Long.valueOf(-result.longValue()) : result;
} catch (NumberFormatException e) {
// If number is Long.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Long.valueOf(constant, radix);
}
return result;
}
That's as close as it can be to the original method (Ctrl+clicking core Java methods is a good experience).
Java doesn't seem to provide one; however, is this code really that cumbersome that you need a library:
public static Long parseBinaryLiteral (String s)
{
if (s == null)
throw new NumberFormatException("null");
// no need to check 0B
s = s.toLowerCase();
String p = "";
if (s.startsWith("0b"))
p = s.substring(2);
else if (s.startsWith("-0b"))
p = "-" + s.substring(3);
else if (s.startsWith("+0b"))
p = s.substring(3);
else
throw new NumberFormatException("For input string: \"" + s + "\"");
return Long.parseLong(p, 2);
}

Method for adding commas to digit string in Java

The assignment is to add comes after every three digits looking from right to left. So number 1000000 should be 1,000,000 etc.
I have relatively good idea how to tackle this problem, but I have no idea why am I getting no output. Maybe I am making some mistake that I am not aware of or something...
I think that I understand concept that Strings are immutable, so they cannot be changed in place and when you want to change something to string you have to make new string object. But I dont get how is this possible then:
`result = ch + result;`
and this
result = "," + result;
What am I getting wrong here ?
import acm.program.*;
import acm.util.*;
public class AddCommasToNumericString extends ConsoleProgram{
public void run(){
while(true){
String digits = readLine("Enter a numeric string: ");
if (digits.length() == 0) break;
println(addCommasToNumericString(digits));
}
}
public String addCommasToNumericString(String digits){
String result = "";
int counter = 0;
for (int i = digits.length()-1; i <= 0 ; i--){
char ch = digits.charAt(i);
result = ch + result;
counter++;
if (counter % 3 == 0){
result = "," + result;
}
}
return result;
}
}
I suggest eliminating the counter and use only the loop variable by making a small change:
public String addCommasToNumericString(String digits) {
String result = "";
for (int i=1; i <= digits.length(); ++i) {
char ch = digits.charAt(digits.length() - i);
if (i % 3 == 1 && i > 1) {
result = "," + result;
}
result = ch + result;
}
return result;
}
addCommasToNumericString("123"); // 123
addCommasToNumericString("12345"); // 12,345
addCommasToNumericString("1234567"); // 1,234,567
Convert the read line into an Integer, then format it as a String
String digits = readLine("Enter a numeric string: ");
Integer myInt = new Integer(digits);
String output = NumberFormat.getNumberInstance(Locale.US).format(myInt.value());

how can I check if a string is a floating point number?

In my program I'm going to store user input in an array then going to check each character to see if it's a digit or dot or E or negative sign after that I'll store it in to an array called temps.
Now I have problem in my fleating method () that don't how should I make my condition for the pattern of floating number digit-digit-dot-digit-digit (e.g 12.22)
I have my work here:
public void sorting(String data) {
String[] temps = new String[200];
int cpos = 0;
int tpos = 0;
Arrays.fill(temps, null);
if (str.isEmpty() == false) {
char char1 = str.charAt(cpos);
int i = 0;
while (i < str.length()) {
char1 = str.charAt(cpos);
char1 = str.charAt(tpos);
System.out.println("the current value is " + char1 + " ");
tpos++;
if (Character.isDigit(char1)) {
temps[cpos] = "Digit";
// System.out.println(" this number is digit");
cpos++;
} else if (char1 == 'e' || char1 == 'E') {
temps[cpos] = "s_notaion";
cpos++;
} else if (char1 == '-') {
temps[cpos] = "negative";
cpos++;
} else if (char1 == '.') {
temps[cpos] = ".";
cpos++;
}
i++;
}
}
}
here is the method for floating number
private static boolean floating(String [] data) {
int count =0;
boolean correct = false;
for (int i = 0; i < data.length; i++) {
if (data[i]== "Digit" )
&& data[i]=="." && data[i]"Digit"){
// here is the problem for the condition
}
}
return false;
}
If I understood correctly, the Data array has stuff like ["Digit","Digit",".","Digit"]
So you want the
private static boolean floating(String [] data) {
method to return true if the array only has "Digit" entries and exactly one "." entry? is that it?
If so:
boolean foundLeDigit = false;
for (int i = 0; i < data.length; i++) {
if (data[i].equals("Digit") == false && data[i].equals(".") == false {
//we found something other than a Digit or . it's not a float
return false;
}
if(data[i].equals(".")) {
if(foundLeDigit) { return false; //as we found 2 "." }
foundLeDigit = true
}
}
return foundLeDigit;
The easiest way to test if a String can represent a float is to try to parse it:
String testString = "1.2345";
double result;
try {
result = Double.parseDouble(testString);
System.out.println("Success!")
}
catch (NumberFormatException nfe) {
// wasn't a double, deal with the failure in whatever way you like
}
The questions lacks a bit of context, so for my answer I'm going to presume that this is homework requiring a manual solution, and that all floating point numbers are supposed to be accepted.
Your approach (while over-engineered) is half-right: you are reducing the input string into classes of characters - digit, sign, exponent marker. What is missing is that now you have to make sure that these character classes come in the right order.
Identify the various parts of float numbers (just look at 0, -1.0, 400E30, 42.1E-30) and you'll see that they come in a specific order, even if some are optional, and that each part imposes restrictions on what characters are allowed there. For example, if there is an 'E' in the number, it has to be followed by a number (with optional sign).
So as you step through the characters of the string, think about how you could keep track of where you are in the number, and base your character validation on that (this is the state machine #JonKiparsky was mentioning).
A few small things:
Don't compare strings with '==' - use equalsTo().
Think about what it means if sorting() finds a character which is neither a digit, a sign, or the exponent 'E'?
You allocate the temps array for 200 entries, but the input string could be larger.
using the regular expression is the best way to Handel this problem
private static boolean floating(String [] data) {
int count =0;
boolean correct = false;
for (int i = 0; i < data.length; i++) {
if (str.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")){
System.out.println(" it's a floating number ");
correct= true;
break;
}else
correct = false;
}if (correct ==true){
return true;
}else
return false;
}

Stack problem java. Postfix Evaluation

Hey Guys I'm having a problem when I run my program. In the PostfixEvaluate() Method is where it takes in a string and solves the postfix problem and returns it. Well when I go to run it, I'm getting a bunch of random numbers(some repeated), I'm going crazy because I don't know what else to try and I've spent more time on this than it should normally take.
Heres the PostfixEvaluate Method:
public int PostfixEvaluate(String e){
//String Operator = "";
int number1;
int number2;
int result=0;
char c;
//number1 = 0;
//number2 = 0;
for(int j = 0; j < e.length(); j++){
c = e.charAt(j);
if (c != '+'&& c!= '*' && c!= '-' && c!= '/') {
//if (c == Integer.parseInt(e)) {
s.push(c);
}
else {
number1 = s.pop();
number2 = s.pop();
switch(c) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '*':
result = number1 * number2;
break;
case '/':
result = number1 / number2;
break;
} s.push(result);
}
System.out.println(result);
}
return s.pop();
}
public static void main(String[] args) {
Stacked st = new Stacked(100);
String y = new String("(z * j)/(b * 8) ^2");
String x = new String("2 3 + 9 *");
TestingClass clas = new TestingClass(st);
clas.test(y);
clas.PostfixEvaluate(x);
}
}
This is the Stack Class:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(int result) {
top++;
stack[top] = (char)result;
}
public int pop() {
int x;
x = stack[top];
//top = top - 1;
top--;
return x;
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty " + "Equation Good");
return true;
}
else
System.out.println("Equation is No good");
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
}
It looks to me like you aren't handling spaces at all.
This means that when you put in a space, it is implicitly converting the character space to the ascii value of it (32) when it pops it off the stack during an operation. Also, it looks like you are assuming that all numbers/results will be single digit, and casting from char to int, which is not what you want to do, since that will convert the char to the ascii value of the char, ' ' -> 32, '3' -> 51, etc.
If I were you, I would do this for your loop in PostfixEvaluate:
while(!e.equals("")){
string c;
int space = e.indexOf(' ');
if(space!=-1){
c = e.substring(0,space);
e = e.substring(space+2);
} else{
c = e;
e = "";
}
if (!c.equals("+")&& !c.equal("*") && !c.equals("-") && !c.equals("/")) {
//...
}
and change your stack to hold strings or ints.
The problem is that you are pushing char onto a stack as an int, so you are unintentionally working with the ascii representations of numbers, which is not the actual value of the number.
Instead of this complicated character walking, tokenize the input string using String.split(). Example:
String[] tokens = e.split(" ");
for(String token:tokens){
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
....
}
}
You need to split the string into tokens first:
/* Splits the expression up into several Strings,
* all of which are either a number or and operator,
* none of which have spaces in them. */
String [] expressionAsTokens = e.split(" ");
Then you need to make sure you compare Strings, not chars:
//compare strings instead of chars
String token = expressionAsTokens[j];
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
//same code as you had before
}
Also, is there any reason you are storing everything as a char array in your Stacked class? Your pop() method returns and integer, yet everything is stored as a char.
For this application, everything should be stored as an integer:
public class Stacked {
int stack[]; // array is of type integer
int top;
int maxLen;
// constructor
public void push() {/*...*/}
public int pop() {/*...*/} //pop returns an int as before
//...
}
One final note: Be careful what order you add and subtract the numbers in. I don't remember if postfix operands are evaluated left first or right first, but make sure you get them in the right order. As you have it now, 2 3 - 4 * would evaluate as 4 * (3 - 2) and I think it should be (2 - 3) * 4. This won't matter with adding and multiplying, but it will with subtracting and dividing.

Categories