lunes, 31 de octubre de 2011

Java Stacks

Well we all know what batteries are in Java, but explain a little as we will need in the implementation of Nachos.

The first is to define the stack, ie, instantiate the class Stack.

Stack pila = new Stack();

When using a string, we mean what are strings.
The method that inserts elements in the stack is. Push (). This method will receive as a parameter the element to be inserted.

for (int x=1;x<=10;x++) pila.push(Integer.toString(x));

We have created a loop that we will create the numbers and we have relied on the Integer class and method. ToString () to convert numbers to strings.

Once we have all the elements, we proceed to drain the battery. We will have to interact on the stack until it is empty, which tells us the method. Empty (). In each iteration we extract an item from the stack using the method. Pop ().

while (!pila.empty())
System.out.println(pila.pop());



This is the code:

import java.util.*;
public class Pilando {
Stack pila = new Stack();
public void ingresar()
{
for (int x=1;x<=3;x++) { pila.push(Integer.toString(x)); } } public void sacar() { while (this.empty() == 1) { System.out.println("Sacando el elemento "+pila.pop()); } System.out.println("La pila esta vacía!!!"); } public void show1() { System.out.println("El primer elemento agregado es ---> "+pila.firstElement().toString());
}
public void show2()
{
System.out.println("El ultimo elemento agregado es ---> "+pila.lastElement().toString());
}
public void show3()
{
System.out.println("La cantidad de elementos es de ---> "+pila.size());
}
public int empty()
{
int valid = 1;
if(!pila.empty())
{
valid = 1;
}
else
if(pila.empty())
{
valid = 0;
}
return valid;
}
}

1 comentario:

  1. Pila != Battery. No uses autotraductores. Y pon tus referencias bibliográficas (http://www.kubuntu-es.org/wiki/crear-pila-java) - simplemente copiar cosas tal cual es plagiarismo y en algunas universidades te suspenden por hacer eso. Esta entrada no otorga puntos extra.

    ResponderEliminar