package javaapplication24;
import java.util.Scanner;
public class InToPost {
private Stack theStack;
private String input;
private String output = "";
public InToPost(String in) {
input = in;
int stackSize = input.length();
theStack = new Stack(stackSize);
}
public String cekoperator() {
for (int j = 0; j < input.length();
j++) {
char cek = input.charAt(j);
switch (cek) {
case '+':
case '-':
gotOper(cek, 1);
break;
case '*':
case '/':
gotOper(cek, 2);
break;
case '^':
case '(':
theStack.push(cek);
break;
case ')':
gotParen(cek);
break;
default:
output = output + cek;
break;
}
}
while (!theStack.isEmpty()) {
output = output + theStack.pop();
}
return output;
}
public void gotOper(char opThis, int cek1) {
while (!theStack.isEmpty()) {
char opTop = theStack.pop();
if (opTop == '(') {
theStack.push(opTop);
break;
}
else {
int cek2;
if (opTop == '+' || opTop == '-')
cek2 =1;
else
cek2 = 2;
if (cek2 < cek1)
{
theStack.push(opTop);
break;
} else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char cek ){
while (!theStack.isEmpty()) {
char pop = theStack.pop();
if (pop == '(')
break;
else
output = output +pop;
}
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Masukkan nilai
infix : ");
String a = input.next();
String output;
System.out.println();
InToPost operator = new InToPost(a);
output = operator.cekoperator();
System.out.println("Hasil postfix :
" + output);
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
Tidak ada komentar:
Posting Komentar