Source Code Main
package stackTandaKurung;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
byte pil;
do{
System.out.println("Program Validasi Tanda Kurung");
System.out.println("1. Validasi");
System.out.println("2. Keluar");
System.out.print("Pilih : ");
pil = s.nextByte();
switch(pil){
case 1 :
cStack stck = new cStack();
System.out.print("Masukkan Persamaan : ");
s = new Scanner(System.in);
String persm = s.nextLine();
boolean valid=false;
for (byte i=0; i < persm.length(); i++) {
char td = persm.charAt(i);
cItem tnd = new cItem(td);
if(td=='(' || td=='{' || td=='[') stck.push(tnd);
else if(td==')' || td=='}' || td==']'){
if(stck.peek()!=null){
cItem tdpop = stck.pop();
if((tdpop.getTanda()=='(' && td==')') || (tdpop.getTanda()=='{' && td=='}') || (tdpop.getTanda()=='[' && td==']')){
valid =true;
}
}
else valid=false;
}
}
if(stck.peek()==null && valid==true) System.out.println("Persamaan Valid!");
else System.out.println("Persamaan Tidak Valid!");
System.out.println(" ");
break;
case 2 : System.out.println("Terima Kasih!");
}
}while(pil!=2);
}
}
Source Code cStack
package stackTandaKurung;
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;
}
}
}
Source Code cItem
package stackTandaKurung;
public class cItem {
private char tanda;
cItem next, prev;
cItem(char t){
tanda = t;
}
public char getTanda(){
return tanda;
}
}
0 Comments