Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Practico2;
- import java.util.Scanner;
- import java.util.Random;
- public class Ejercicio3 {
- static Random aleatorio = new Random();
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //Stack <String> stack=new Stack();
- menu();
- }
- public static void menu() {
- Stack<Character> pila = new Stack<Character>();
- int opcion, seguir;
- String expres;
- do {
- System.out.println("1 - Ingresar una expresion por consola");
- System.out.println("2 - Generar una expresion aleatoria");
- opcion = Helper.getPositiveInt("Ingrese una opcion valida");
- switch(opcion){
- case 1:
- System.out.println("Ingrese una expresion");
- expres = cargarExpresion();
- pasarPost(pila, expres);
- break;
- case 2:
- expres = generarExpresion();
- System.out.println("La expresion " + expres + " en notacion PostFija es:");
- pasarPost(pila, expres);
- break;
- default:
- System.out.println("Opcion no valida");
- }
- seguir=Helper.getPositiveInt("Desea ingresar otra expresion??(1=Si//2=No)");
- }while(seguir !=2);
- System.out.println("Gracias :D");
- }
- public static String cargarExpresion() {
- Scanner sc = new Scanner(System.in);
- String aux;
- aux = sc.nextLine();
- return aux;
- }
- public static String generarExpresion() {
- String[] expr= {"2+5", "(a*b)+c", "((2*6)/3)+9",
- "(4/2)+6", "7-8", "((3*y)+(2*x))/2",
- "(2*a)+ b", "(3*b)-a"};
- int i =aleatorio.nextInt(expr.length-1);
- return expr[i];
- }
- public static void pasarPost(Stack<Character> pila, String expres) {
- String aux ="";
- for (int i = 0; i < expres.length(); i++) {
- if(expres.charAt(i)>='0'&&expres.charAt(i)<='9'|| expres.charAt(i)>='a'&&expres.charAt(i)<='z') {
- aux = aux+expres.charAt(i);
- }
- if(expres.charAt(i) >='*' && expres.charAt(i) <= '/') {
- pila.push(expres.charAt(i));
- }
- if(expres.charAt(i) == ')') {
- aux = aux+pila.pop();
- }
- }
- while(!pila.empty()) {
- aux = aux + pila.pop();
- }
- System.out.println(aux);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement