Search
Stack Java : Validasi Tanda Kurung

Source code Progam
appStack
StackKurung;
import java.util.Scanner;
public class appStack {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int pilih;
do{
System.out.println("");
System.out.println("PROGRAM VALIDASI");
System.out.println("1. Validasi Tanda Kurung");
System.out.println("2. Keluar");
System.out.print("Pilih : ");
pilih = s.nextInt();
switch(pilih){
case 1:
cStack stack = new cStack();
System.out.print("Masukkan persamaan : ");
s = new Scanner(System.in);
String pers = s.nextLine();
boolean valid = false;
for(int i = 0; i < pers.length(); i++){
char t = pers.charAt(i);
cItem td = new cItem(t);
if(t=='('||t=='{'||t=='['){
stack.push(td);
}else if(t==')'||t=='}'||t==']'){
if(stack.peek()!=null){
cItem tpop = stack.pop();
if((tpop.getTanda()=='('&& t ==')'||tpop.getTanda()=='{'&&t=='}'||tpop.getTanda()=='['&& t==']')){
valid = true;
}
}else{
valid = false;
}
}
}
if(stack.peek()==null&&valid==true){
System.out.println("Persamaan Valid(pasangannya)");
}else if(stack.peek()!=null&&valid==true){
System.out.println("Persamaan Tidak VALID(tidak ada pasangannya)");
}else{
System.out.println("Persamaan Tidak VALID(bukan pasangan)");
}
break;
case 2:
System.out.println("Terima Kasih");
}
}while(pilih!=2);
}
}cStack
package StackKurung;
public class cStack {
cItem top, bottom, temp;
cStack(){
top = bottom = null;
}
public void push(cItem baru){
if(top == null){
top = bottom = baru;
}else{
top.prev = baru;
baru.next = top;
top = baru;
}
}
public cItem pop(){
if(top == null){
return null;
}else if(top.next == null){
temp = top;
top = bottom = null;
return temp;
}else{
temp = top;
top = top.next;
temp.next = temp.prev = null;
return temp;
}
}
public cItem peek(){
if(top == null){
return null;
}else{
return top;
}
}
}cItem
package StackKurung;
public class cItem {
private char tanda;
cItem next, prev;
cItem(char t){
tanda = t;
}
public char getTanda(){
return tanda;
}
}Hasil Program




Comments