Advertisement
Guest User

Untitled

a guest
Mar 28th, 2016
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1.  
  2.  
  3. public class InfixtoPostfix2
  4. {
  5. Stos stos = new Stos();
  6. String postFix="";
  7. public boolean isOperator(char c){
  8. return c == '+'||c== '-'||c=='*'||c=='/';
  9. }
  10. public int priorytet(char operator)
  11. {
  12. if(operator=='+' || operator=='-') return 1;
  13. else if(operator=='*' || operator=='/') return 2;
  14. else return 0;
  15. }
  16.  
  17. public void proccessOperator(char op)
  18. {
  19. char topOp ;
  20. if(stos.isEmpty())
  21. {
  22. stos.push(op);
  23. }else{
  24. topOp=stos.peek();
  25. if(priorytet(op)>priorytet(topOp))
  26. {
  27. stos.push(op);
  28. }else{
  29. while(stos.isEmpty()==false&&priorytet(op)<=priorytet(topOp)){
  30. postFix+= stos.pop();
  31.  
  32. if(stos.isEmpty()==false){
  33. topOp=stos.peek();
  34. stos.push(op);
  35.  
  36. }
  37. }
  38. }
  39. }
  40. }
  41. public void convert(String infix)
  42. {
  43. for(int i =0;i<infix.length();i++)
  44. {
  45. if(isOperator(infix.charAt(i))==false){
  46. postFix+=infix.charAt(i);
  47. }else if(isOperator(infix.charAt(i))==true){
  48. proccessOperator(infix.charAt(i));
  49.  
  50. }else{
  51. System.out.println("Zle dane");
  52. }
  53. }
  54.  
  55. System.out.print(postFix);stos.display();
  56.  
  57.  
  58. }
  59. public static void main(String[] args)
  60. {
  61. InfixtoPostfix2 test2 = new InfixtoPostfix2();
  62. InfixtoPostfix2 test3 = new InfixtoPostfix2();
  63. test2.convert("1+2/3"); //wynik 123/+
  64. System.out.println();
  65. test3.convert("2+3-1"); //wynik 23+1
  66. }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement