Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.NoSuchElementException;
  5.  
  6. public class Zagradi<E>{
  7. public static class ArrayStack<E> {
  8.  
  9. // Stekot e pretstaven na sledniot nacin:
  10. //depth e dlabochinata na stekot, a
  11. // elems[0...depth-1] se negovite elementi.
  12. private E[] elems;
  13. private int depth;
  14.  
  15. @SuppressWarnings("unchecked")
  16. public ArrayStack (int maxDepth) {
  17. // Konstrukcija na nov, prazen stek.
  18. elems = (E[]) new Object[maxDepth];
  19. depth = 0;
  20. }
  21.  
  22.  
  23. public boolean isEmpty () {
  24. // Vrakja true ako i samo ako stekot e prazen.
  25. return (depth == 0);
  26. }
  27.  
  28.  
  29. public E peek () {
  30. // Go vrakja elementot na vrvot od stekot.
  31. if (depth == 0)
  32. throw new NoSuchElementException();
  33. return elems[depth-1];
  34. }
  35.  
  36.  
  37. public void clear () {
  38. // Go prazni stekot.
  39. for (int i = 0; i < depth; i++) elems[i] = null;
  40. depth = 0;
  41. }
  42.  
  43.  
  44. public void push (E x) {
  45. // Go dodava x na vrvot na stekot.
  46. elems[depth++] = x;
  47. }
  48.  
  49.  
  50. public E pop () {
  51. // Go otstranuva i vrakja elementot shto e na vrvot na stekot.
  52. if (depth == 0)
  53. throw new NoSuchElementException();
  54. E topmost = elems[--depth];
  55. elems[depth] = null;
  56. return topmost;
  57. }
  58. }
  59. public static boolean isDigit(char x) {
  60. int a = (int) x;
  61. return( a == 1 || a == 2 || a == 3 || a == 4 || a == 5 || a == 6 || a == 7 || a == 8 || a == 9);
  62. }
  63.  
  64. public static int evaluacija (char exp[]) {
  65. ArrayStack<Integer> stekce = new ArrayStack<Integer>(100);
  66. for(int i=0;i<exp.length;i++) {
  67. if (isDigit(exp[i])) {
  68. int a = (int) exp[i];
  69. stekce.push(a);
  70. }
  71. else if (exp[i] == '+' || exp[i] == '*') {
  72. int x = stekce.pop();
  73. int y = stekce.pop();
  74. if (exp[i] == '+') {
  75. int z = x + y;
  76. stekce.push(z);
  77. }
  78. if (exp[i] == '*') {
  79. int z = x * y;
  80. stekce.push(z);
  81. }
  82. }
  83. }
  84. return stekce.pop();
  85. }
  86.  
  87.  
  88. public static void main (String[] args) throws IOException {
  89. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  90.  
  91. String expression = br.readLine();
  92. char exp[] = expression.toCharArray();
  93. int x = evaluacija(exp);
  94. System.out.print(x);
  95.  
  96. br.close();
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement