Last active
August 29, 2015 14:06
-
-
Save Krewn/f6c6e6f35526609f310a to your computer and use it in GitHub Desktop.
Polish notation JavaStackImpl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package prefixNotation; | |
public class prefix { | |
/** | |
* @param args | |
*/ | |
public static String reverse(String input){ | |
if(input.length()==1){ | |
return(input); | |
}else{ | |
return(reverse(input.substring(1,input.length()))+input.charAt(0)); | |
} | |
} | |
public static double prefixEval(String input){ | |
java.util.Stack<Double> s = new java.util.Stack<Double>(); | |
//input | |
System.out.println(input); | |
input=reverse(input); | |
int k2; | |
String c; | |
for(int k = 0 ; k < input.length() ; k++){ | |
c = input.substring(k,k+1); | |
try{ | |
k2=0; | |
while(!input.substring(k+k2,k+k2+1).equals("/") && !input.substring(k+k2,k+k2+1).equals("*") && !input.substring(k+k2,k+k2+1).equals("-") && !input.substring(k+k2,k+k2+1).equals("+") && !input.substring(k+k2,k+k2+1).equals(",")){ | |
k2++; | |
} | |
k+=k2; | |
s.push(Double.parseDouble(reverse(input.substring(k-k2,k)))); | |
k--; | |
} | |
catch(Exception NumberFormatException){ | |
if(c.equals("+")){ | |
s.push(s.pop()+s.pop()); | |
} | |
if(c.equals("-")){ | |
s.push(s.pop()-s.pop()); | |
} | |
if(c.equals("/")){ | |
s.push(s.pop()/s.pop()); | |
} | |
if(c.equals("*")){ | |
s.push(s.pop()*s.pop()); | |
} | |
} | |
} | |
return(s.pop()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment