-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidarPosfija.java
More file actions
94 lines (81 loc) · 3.47 KB
/
ValidarPosfija.java
File metadata and controls
94 lines (81 loc) · 3.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.*;
public class ValidarPosfija {
public static void main(String[] args) {
// Crear la interfaz gráfica
JFrame frame = new JFrame("Validador de Expresiones Posfijas");
JTextField textField = new JTextField(20);
JButton button = new JButton("Validar");
JLabel label = new JLabel("Ingresa una expresión posfija:");
frame.setLayout(new java.awt.FlowLayout());
frame.add(label);
frame.add(textField);
frame.add(button);
// Acción del botón
button.addActionListener(e -> {
String input = textField.getText().trim();
if (esPosfijaValida(input)) {
JOptionPane.showMessageDialog(frame, "Expresión posfija válida.");
} else {
JOptionPane.showMessageDialog(frame, "Expresión posfija inválida.");
}
});
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
// Método para validar la expresión posfija
public static boolean esPosfijaValida(String exp) {
Stack<Integer> stack = new Stack<>();
// Separar los elementos usando una expresión regular
String[] tokens = separarTokens(exp);
for (String token : tokens) {
// Si el token es un número o una variable, lo apilamos
if (esNumero(token) || esVariable(token)) {
stack.push(1); // Apilamos un operando
} else if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
// Necesitamos al menos dos operandos para aplicar el operador
if (stack.size() < 2) {
return false;
}
// Aplicamos el operador (aunque no lo hacemos realmente)
stack.pop(); // Operando 1
stack.pop(); // Operando 2
stack.push(1); // Apilamos el resultado de la operación
} else {
// Si el token no es un operador válido, es inválido
return false;
}
}
// Al final, debería quedarnos solo un elemento en la pila (el resultado)
return stack.size() == 1;
}
// Método para verificar si el token es un número
public static boolean esNumero(String token) {
try {
Integer.parseInt(token); // Intentar convertir el token a un número
return true;
} catch (NumberFormatException e) {
return false;
}
}
// Método para verificar si el token es una variable (letra)
public static boolean esVariable(String token) {
return token.matches("[a-zA-Z]"); // Comprobar si el token es una letra
}
// Método para separar los tokens (números, letras y operadores)
public static String[] separarTokens(String input) {
// Usar una expresión regular para separar los números, letras y operadores
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]+|[-+*/]");
Matcher matcher = pattern.matcher(input);
// Crear una lista de tokens encontrados
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
sb.append(matcher.group()).append(" ");
}
// Devolver los tokens separados en un arreglo
return sb.toString().trim().split("\\s+");
}
}