Skip to main content

Source Code Calculator Infix-Postfix Java

Kali ini saya akan posting tentang source codenya calculator infix-postfix dengan menggunakan Java. Semoga bermanfaat:)


package calculator;
import static java.lang.System.in;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

/**
 *
 * @author Acer
 */
public class calculator {
    public static String inputan;
    boolean debug;
    final String operands = "^*+-/" ;
double result;
final static int PLUS=  1;
final static int MINUS=  1;
final static int PERKALIAN=  2;
final static int PEMBAGIAN=  2;
final static int PANGKAT=  3;
final static int PARANTHESIS=  4;
        public calculator(boolean db){
debug  = db;
}

    private calculator(String inputan) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    public  String inputan(String in){
        inputan=in;
        return null;
    }  
    public int operator(String op){
if( op.equals("+"))
return calculator.PLUS ;
else if( op.equals("-"))
return calculator.MINUS;
else if( op.equals("*"))
return calculator.PERKALIAN ;
else if( op.equals("^"))
return calculator.PANGKAT ;
else if( op.equals("/") )
return calculator.PEMBAGIAN ;
else
return calculator.PARANTHESIS;
}


public boolean Operand(String s, boolean Paranthesis){
s = s.trim();
if (s.length() != 1 )
return false;
if (Paranthesis &&  ( s.equals("(") ||  s.equals(")") ) )
return true;
else return operands.indexOf( s ) != -1 ;
}
        public boolean Angka(String s){
String  master="-0123456789.";
s = s.trim();
for( int i = 0;i < s.length()  ;i++)
{
String lttr = s.substring(i, i+1);
if(master.indexOf( lttr) == -1)
return false;
}
return true ;
}
public void parseRPN(String input){
String rpnStr = input;
String[] inputan = rpnStr.split("\\s+");//remove all white space
Stack<Double> inputStack =new Stack<Double>();

boolean  bAllowParenthesis = false;
                       for( String in : inputan){
                            if(in.equals("-")==false && Angka(in ))
{
double d = Double.parseDouble( in  ) ;
inputStack.push(d ) ;
}
                            else if( Operand( in , bAllowParenthesis   ) ){
if( inputStack.size() <  2 ){
                                    System.out.println("Operator "+in+ " tidak valid ");
                                    return;
                                    }
                            double no1 = inputStack.pop();
                            double no2 = inputStack.pop() ;
                            double result = this.hitung( no2 , no1 , in  ) ;
                            inputStack.push( result);
                            }
                            else if( in.trim().length() > 0 )
System.out.println( in + " is invalid, only use numbers or operators " );
}
                        result= inputStack.pop();
}
double getResult() {
return result;
}
    private Double hitung(double no1, double no2, String op ) {
if( op.equals("+"))
return no1 + no2;
else if( op.equals("-"))
return no1 - no2;
else if( op.equals("*"))
return no1 * no2;
else if( op.equals("^"))
return Math.pow(no1 , no2 );
else if( op.equals("/") ){
if(no2 ==0 )
throw new ArithmeticException("0");
return no1 / no2;
}
else{
                    System.out.println(op + " is not a supported operand") ;
                    return null;
                }
}
public ArrayList<String> infixToPostfix(String input){

ArrayList<String> output  = new ArrayList<String>();
input = input.replaceAll("\\s+","") ;
Stack<String> operandStack = new Stack<String>();
for(int i = 0 ;i< input.length() ; i++){
                    String currentIn = input.substring(i,i+1);
                    if( Operand(currentIn, true)){
                        if( operandStack.size() == 0) operandStack.push( currentIn );
                        else if(operandStack.size() > 0  && currentIn.equals(")" ) ){
while( operandStack.size() > 0  && operandStack.peek().equals("(" ) == false){
                                output.add( operandStack.pop() ) ; }
operandStack.pop();
                        }else if(operandStack.size() > 0 ){
                            if( (currentIn.equals("(") && operandStack.peek().equals("(") ) ||
                                (currentIn.equals("(")== false &&  this.operator( operandStack.peek() )
                                    >= this.operator(currentIn) ) ){
                            while (operandStack.size()> 0 && operandStack.peek().equals("(")== false &&
                                   this.operator( operandStack.peek() ) >= this.operator(currentIn)){  //this.p("III pop off " + operands.peek() +", greater than " + currentToken +",current  out: "+ output.toString().replaceAll(",", " " ) );
  output.add(operandStack.pop() );
                                   }
  operandStack.push( currentIn ) ;
  }
                            else if( this.operator( operandStack.peek() ) < this.operator(currentIn) ){
                                    operandStack.push( currentIn ) ;}
}
                    }else if ( Angka( currentIn ) ){

                    ulangAngka : while(  i+1 < input.length()){
                    String nxtLttr =  input.substring(i+1,i+2);
                    if(nxtLttr.equals("-") )
                    break ;
                    if( Angka(nxtLttr ) ){
                        currentIn +=nxtLttr;
                        i++;
                    }else
                    break ulangAngka;
                    }
                    try{
output.add(currentIn) ;
                    }
                    catch (NumberFormatException e){  System.out.println(currentIn + " angka tidak valid"); }
                    }
                }

while( operandStack.size() > 0 ){
this.p("V pop off " + operandStack.peek() +" and add to output" );
output.add( operandStack.pop() ) ;
}
return output;
}
void p(String s){
if(this.debug)
System.out.println(s);
        }

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner input = new Scanner(System.in);
        boolean debug = false;
calculator rp = new calculator(debug );
        ArrayList<String> asPostfix ;
        String DataInfix="" ;
System.out.println("Data Infix anda : " ) ;
                DataInfix=input.next();
asPostfix =  rp.infixToPostfix(DataInfix);
String hasilPostfix = asPostfix.toString().replaceAll(",", " " ) ;
hasilPostfix = hasilPostfix.substring(1, hasilPostfix.length()-1 ) ;
System.out.println("Postfix " +  hasilPostfix);
System.out.println("Hasil : ");
rp.parseRPN( hasilPostfix ) ;
                System.out.println( DataInfix + " =  " + rp.getResult() ) ;
    }
}


Berikut hasil running outputnya:


Comments

Post a Comment

Popular posts from this blog

TRIK MUDAH JADIKAN SMARTPHONE / ANDROID JADI DRAWING PAD/PEN TABLET

Punya hobi menggambar? kamu tidak perlu buru-buru beli drawing pad, manfaatkan saja smartphone yang kamu miliki. Yap bagi kalian yang suka mendesain pasti tahu apa itu drawing pad, drawing pad adalah hardware untuk menggambar dengan tangan atau stylus pen, hasil gambar dapat dilihat didalam layar komputer, seperti menggambar manual menggunakan pensil. Trik mudah untuk mengubah smartphone menjadi drawing pad : 1. Download Aplikasi Spacedesk di smartphone, kalian bisa langsung download di playstore. 2. Download Aplikasi Spacedesk Server untuk komputer/laptop, dapat di donwload pada link berikut https://spacedesk.net/ 3. Install dilaptop dan smartphone kalian. 4. Setelah terinstall hubungkan kedua perangkat, bisa menggunakan kabel usb dengan mode develop, dan juga menggunakan 1 jaringan yang sama. 5. Buka aplikasi di kedua perangkat. 6. Kemudian saat kedua perangkat sudah terhubung -> Connect to Primary Machine (Server) -> pilih IP laptop anda. Smartphone sudah dapat dijadikan draw

Tutorial Mudah Mengubah Warna Cell Dengan Checkbox Spreadsheet

Cara mudah untuk mengubah warna cell dengan pengecekan jika checkbox -> checked maka cell akan berubah warna.  1. Buat tabel dengan beberapa kolom Tabel Data 2. Pilih menu ->   Sisipkan->kotak centang 3. Pilih menu   Format->format bersayarat 4.    Blok cell yang akan diwarna Pilih rentang data-> mulai kolom B baris 2 sampai B7     5.  Pilih format sel ->Formula khususnya adalah -> inputkan cell checkbox ,C2 adalah posisi kolom checkbox kolom C baris 2, rumusnya adalah =C2=TRUE artinya jika checkbox checked = TRUE, jika TRUE set warna kolom nama.     6.  Pilih Gaya pemformatan ->colour ->selesai  Dan hasilnya ketika checkbox di checked maka kolom nama akan berubah warna. Mudah bukan?  d f

Flowchart & Source code Stack pada DevC++

Flowchart & Source code Stack pada DevC++ Flowchart Sourcecode Stack pada DevC++