fork download
  1. import java.util.Stack;
  2. import java.util.Scanner;
  3.  
  4. class Stacks {
  5. public static int evaluarop(String string) { //Pasar el string a un arreglo de Char;
  6. // index nombre del arreglo de Chars para saber en que char va.
  7. char[] index = string.toCharArray();
  8.  
  9. // Crea un Stack 'numero' de tipo Integer con la clase Stack<E>
  10. Stack<Integer> numero = new Stack<Integer>();
  11.  
  12. // Crea un Stack 'simbolo' de tipo Character con la clase Stack<E>
  13. Stack<Character> simbolo = new Stack<Character>();
  14.  
  15. //For inicia el bucle
  16. for (int i = 0; i < index.length; i++)
  17. {
  18. System.out.println("Examining char "+i+" :"+index[i]);
  19.  
  20. // Index = char actual
  21. // Index en la posición actual es un espacio en blanco, pasar al siguiente char.
  22. if (index[i] == ' ')
  23. continue;
  24.  
  25. // Si el index actual es un numero ponerlo en el stack de numero.
  26. // Si el index es un char del 0 al 9
  27. if (index[i] >= '0' && index[i] <= '9')
  28. {
  29. // If pregunta si el index es un char del 0 al 9
  30. // StringBuffer() = construye un string de almacenamiento sin caracteres
  31. // y con capacidad inicial de 16 caracteres
  32. StringBuffer sbuf = new StringBuffer();
  33. // Si es un numero formado por mas de un digito.
  34. while (i < index.length && index[i] >= '0' && index[i] <= '9')
  35. sbuf.append(index[i++]);
  36. // Inserta en el Stack de numeros.
  37. // ParseInt pasa el String y lo retorna como un entero.
  38. //i--;
  39. numero.push(Integer.parseInt(sbuf.toString()));
  40. }
  41.  
  42. // Si el index acutal es '(', hacer push a stack simbolo.
  43. else if (index[i] == '(')
  44. simbolo.push(index[i]);
  45.  
  46. // Si el index actual es ')' prepara para hacer la operacion.
  47. else if (index[i] == ')')
  48. {
  49. // While peek para ver el simbolo actual hasta que no sea un (.
  50. while (simbolo.peek() != '(')
  51. // Hace el push al resultado de la operacion.
  52. // operandop() hace la operacion correspondiente al char de simbolo correspondiente.
  53. // Numero.pop() agarra el numero para operar.
  54. numero.push(operando(simbolo.pop(), numero.pop(), numero.pop()));
  55. // Quita del arreglo el simbolo ya utilizado.
  56. simbolo.pop();
  57. }
  58.  
  59. // Si el index actual es un simbolo de operación.
  60. else if (index[i] == '+' || index[i] == '-' || index[i] == '*' || index[i] == '/')
  61. {
  62. // While si el char hasta arriba del Stack simbolo tiene la misma o mayor
  63. // jerarquia de operaciones que el char de simbolo.
  64. // Aplica el operador en la cima del Stack simbolo
  65. // Mientras que el Stack de simbolo no esta vacio hace lo anterior.
  66. while (!simbolo.empty() && prioridad(index[i], simbolo.peek()))
  67. numero.push(operando(simbolo.pop(), numero.pop(), numero.pop()));
  68.  
  69. // Hace Push al char actual del Stack simbolo
  70. simbolo.push(index[i]);
  71. }
  72. }
  73.  
  74. while (!simbolo.empty())
  75. numero.push(operando(simbolo.pop(), numero.pop(), numero.pop()));
  76. // Stack numero contiene el resultado, hace pop() para regresarlo.
  77. return numero.pop();
  78. }
  79.  
  80. // Si la operacion2 es de mayor importancia que operacion1; regresa true
  81. public static boolean prioridad(char operacion1, char operacion2)
  82. {
  83. if (operacion2 == '(' || operacion2 == ')')
  84. return false;
  85. if ((operacion1 == '*' || operacion1 == '/') && (operacion2 == '+' || operacion2 == '-'))
  86. return false;
  87. else
  88. return true;
  89. }
  90.  
  91. // Aplica la operación correspondiente mediante un switch con el caracter de simbolo.
  92. // Regresa el resultado.
  93. public static int operando(char operacion, int num1, int num2)
  94. {
  95. switch (operacion)
  96. {
  97. case '+':
  98. return num1 + num2;
  99. case '-':
  100. return num1 - num2;
  101. case '*':
  102. return num1 * num2;
  103. case '/':
  104. return num1 / num2;
  105. }
  106. return 0;
  107. }
  108.  
  109. // Main probador
  110. public static void main(String[] args)
  111. {
  112. System.out.println("Operaciones con stacks.");
  113. Scanner sc = new Scanner(System.in);
  114. //int totalop = sc.nextInt();
  115. //for(int i = 0; i < totalop;i++)
  116. //{
  117. System.out.println("Op: ");
  118. //String string = sc.nextLine();
  119. //System.out.println(Stacks.evaluarop(string));
  120. System.out.println(Stacks.evaluarop("10+2*6"));
  121. System.out.println(Stacks.evaluarop("10 + 2 * 6"));
  122. }
  123. }
Success #stdin #stdout 0.05s 321344KB
stdin
Standard input is empty
stdout
Operaciones con stacks.
Op: 
Examining char 0 :1
Examining char 3 :2
Examining char 5 :6
6
Examining char 0 :1
Examining char 3 :+
Examining char 4 : 
Examining char 5 :2
Examining char 7 :*
Examining char 8 : 
Examining char 9 :6
22