Skip to content

Instantly share code, notes, and snippets.

@carlossaraiva
Created March 8, 2012 21:20
Show Gist options
  • Save carlossaraiva/2003510 to your computer and use it in GitHub Desktop.
Save carlossaraiva/2003510 to your computer and use it in GitHub Desktop.
[ESD] Trabalho sobre pilha
/**
* @author Carlos Eduardo Saraiva
*/
import java.io.IOException;
import java.util.Scanner;
public class Carlos {
public static int top = -1;
public static char[] pilha = new char[100];
public static void main(String[] args) {
boolean continuar = true;
System.out.println("PARENTHESES VERIFICATOR 3001! VER. 000000000000000(humpf)000000000.1");
while (continuar){
char[] expressao = new char[10];
int tamanho = entradaCaractere(expressao);
balanceamento(tamanho, expressao);
if(empty()){
System.out.println("Está balanceada!");
}
else{
System.out.println("Não está balanceada! Danger, danger, system collapsing.. bleep..bleep..");
}
continuar = saida();
}
}
//Verficação do balancemento dos parenteses, colchetes e chaves
public static void balanceamento(int tamanho, char[] expressao){
char auxList[] = {'(', ')', '[', ']', '{', '}'};
int i, j;
for (i = 0; i <= tamanho; i++) {
for (j = 0; j < auxList.length; j++) {
if (verificao(expressao, i) && expressao[i] == auxList[j]) {
pop();
} else {
if (expressao[i] == auxList[j]) {
push(expressao[i]);
}
}
}
}
}
public static boolean verificao(char expressao[], int i) {
if ((top > -1 && (expressao[i] == ')' && pilha[top] == '(' || expressao[i] == ']' && pilha[top] == '[' || expressao[i] == '}' && pilha[top] == '{'))) {
return true;
}
else {
return false;
}
}
public static boolean saida(){
Scanner in = new Scanner(System.in);
System.out.println("Deseja verificar outra expresssao? (Tecle 's para continuar, qualquer outra tecla para sair)");
String op = in.next();
if("s".equals(op) || "S".equals(op)){
return true;
}
else{
System.out.println("bye!");
return false;
}
}
//Método que recebe a entrada do usuário, que digitará a expressão matemática.
public static int entradaCaractere(char vetCar[]) {
char c = 0;
int i = 0;
System.out.println("\n\nDigite a expressão aritimética a ser avaliada:\n\n");
while (i < vetCar.length && c != '\n') {
try {
c = (char) System.in.read();
} catch (IOException erro) {
System.err.println(erro.getMessage());
}
vetCar[i++] = c;
}
return i - 1;
}
//Métodos relacionados a manipulação da pilha
public static void push(char elemento) {
if (!full()) {
top++;
pilha[top] = elemento;
}
}
public static void pop() {
if (!empty()) {
top = top - 1;
}
}
public static boolean empty() {
if (top < 0) {
return true;
} else {
return false;
}
}
public static boolean full() {
return top == pilha.length - 1;
}
public static void mostraPilha() {
for (int i = 0; i <= top; i++) {
if (i == 0) {
System.out.print("[ ");
}
if (i < top) {
System.out.print(pilha[i] + ", ");
} else {
System.out.print(pilha[i] + " ]\n");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment