Queue Stack Reverse Polish Notation Learn programming Java



Lesson:

Dynamic Memory Management


Exercise:

Queue Stack Reverse Polish Notation


Objetive:

Create a program that reads a Reverse Polish Notation expression from a text file, for example:

3 4 6 5 - + * 6 +
(Result 21)

Each item will be stored in a queue. Once the queue has all the items stored, you will need to transfer them from the queue to a stack using the Queue and Stack classes provided in java.

Finally, you will operate with the stack to get the correct result of the RPN expression and show it on the console.


Code:

package FileTextQueue;
import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		System.out.print("Introduce el nombre del archivo: ");
		String nombreFichero = new Scanner(System.in).nextLine();

		if (!(new java.io.File(nombreFichero)).isFile())
		{
			System.out.print("El archivo no existe");
			return;
		}

		try
		{
			boolean depurando = true;

			java.io.FileReader ficheroTexto;
		    java.io.BufferedReader ficheroTextoBufferedReader = 
            new java.io.BufferedReader(ficheroTexto);

			ficheroTexto = new java.io.FileReader(nombreFichero);
			String line = " ";

			LinkedList micola = new LinkedList();

			do
			{
				line = ficheroTextoBufferedReader.readLine();
				if (line != null)
				{
					micola.offer(line);
				}
			} while (line != null);

			ficheroTexto.close();

			Stack miPila = new Stack();

			int numero1 = 0, numero2 = 0;

			int cantidadCola = micola.size();

			String valorCola;
			String[] valores_linea;

			for (int i = 0; i < cantidadCola; i++)
			{
				valorCola = (String)micola.poll();
				valores_linea = valorCola.split("[ ]", -1);

				for (int c = 0; c < valores_linea.length; c++)
				{
					switch (valores_linea[c])
					{
						case "+":
							numero1 = (int)miPila.pop();
							numero2 = (int)miPila.pop();

							miPila.push(numero2 + numero1);

							break;
						case "-":
							numero1 = (int)miPila.pop();
							numero2 = (int)miPila.pop();

							miPila.push(numero2 - numero1);
							break;
						case "*":
							numero1 = (int)miPila.pop();
							numero2 = (int)miPila.pop();

							miPila.push(numero2 * numero1);
							break;
						case "/":
							numero1 = (int)miPila.pop();
							numero2 = (int)miPila.pop();

							miPila.push(numero2 / numero1);
							break;
						default:
							// Almacenamos valores enteros
							miPila.push(valores_linea[c]);
							break;
					}
				}

				for (int j = 0; j < miPila.size(); j++)
				{
					System.out.println(miPila.pop());
				}
			}

			if (depurando)
			{
				new Scanner(System.in).nextLine();
			}
		}

		catch (RuntimeException e)
		{
			System.out.println("Error, " + e.getMessage());
		}
	}
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.