Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import tp0.Helper;
- public class Tp4ejercicio2 {
- static Scanner sc = new Scanner(System.in);
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int opcion;
- String entrada = "";
- System.out.println("Ejercicio 2 Tp 4");
- System.out.println("Dada una operación, confirmaremos si su parentización es correcta");
- do {
- opcion = menu();
- switch (opcion) {
- case 1:
- System.out.println("Ingrese una operación");
- entrada = sc.nextLine();
- verificar(entrada);
- break;
- case 2:
- entrada = generarOperacion();
- verificar(entrada);
- break;
- case 3:
- System.out.println("Programa Terminado");
- break;
- default:
- System.out.println("No es una opción correcta ");
- break;
- }
- }while(opcion!=3);
- }
- public static int menu() {
- int op;
- System.out.println();
- System.out.println("1.Ingresar manualmente");
- System.out.println("2.Generar aleatoriamente");
- System.out.println("3.Salir");
- op = Helper.getPositiveInt("Ingrese una opcion");
- return op;
- }
- public static StackSLL<Character> cargarStack(String cadena){
- StackSLL<Character> operacion = new StackSLL<>();
- for(char c: cadena.toCharArray()) {
- operacion.push(c);
- }
- return operacion;
- }
- public static String generarOperacion(){
- String[] operaciones = {"(2+3)*5","5/)2+1(","12-1*3)","5-2(-2","4*(3+22)","3*(3-2"};
- String op = operaciones[Helper.random.nextInt(operaciones.length-1)];
- System.out.println("La operación generada es: "+op);
- return op;
- }
- public static void verificar(String operacion) {
- boolean correcto = true;
- StackSLL<Character> stack = new StackSLL<Character>();
- for(char c: operacion.toCharArray()) {
- if (esApertura(c)) {
- stack.push(c);
- }
- if (esCierre(c)&stack.empty()) {
- correcto = false;
- break;
- }
- if (esCierre(c)&!stack.empty()) {
- if(stack.peek()!=inverso(c)) {
- correcto = false;
- break;
- }else {
- stack.pop();
- }
- }
- }
- if(!stack.empty())correcto = false;
- if (correcto) {
- System.out.println("La parentizacion es correcta");
- }else {
- System.out.println("La parentizacion NO es correcta");
- }
- }
- public static boolean esApertura(char c) {
- char[] apertura = {'(','{','['};
- for(int i = 0; i<apertura.length;i++) {
- if(c==apertura[i])return true;
- }
- return false;
- }
- public static boolean esCierre(char c) {
- char[] cierre = {')','}',']'};
- for(int i = 0; i<cierre.length;i++) {
- if(c==cierre[i])return true;
- }
- return false;
- }
- public static char inverso(char c) {
- char[] apertura = {'(','{','['};
- char[] cierre = {')','}',']'};
- for(int i = 0; i<apertura.length;i++) {
- if(c==apertura[i])return cierre[i];
- }
- for(int i = 0; i<cierre.length;i++) {
- if(c==cierre[i])return apertura[i];
- }
- return ' ';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement