Tuesday, February 28, 2023

Cara membuat kalkulator dengan bahasa pemrograman java

Kami akan berikan 2 bagian source code atau free source code membuat calculator sederhana secara lengkap melalui Github.

Berikut source code untuk versi CLI

/*

 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license

 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template

 */

package calculator;


/**

 *

 * @author Ahroi

 */


import java.util.Scanner;


public class Calculator {


    public static void main(String args[])

    {

        Scanner input = new Scanner(System.in);

        int num1, num2, optS ,res = 0;

        System.out.println("PROGRAM JAVA CALCULATOR WITH CLI");

        System.out.println("1. Penjumlahan - Add (+)");

        System.out.println("2. Pengurangan - Sub (-)");

        System.out.println("3. Perkalian - Mul (*)");

        System.out.println("4. Pembagian - Div (/)");

        System.out.println("----------------------------");

        System.out.print("Operator (enter): ");

        optS=input.nextInt();

        System.out.print("Num 1 (enter): ");

        num1=input.nextInt();

        System.out.print("Num 2 (enter): ");

        num2=input.nextInt();

                 

        switch (optS){

             case 1 -> res=num1+num2;

             case 2 -> res=num1-num2;

             case 3 -> res=num1*num2;

             case 4 -> res=num1/num2;

             default -> System.out.println("Option Error!");

        }         

        System.out.println("Result :"+res);

    }

    

}


Untuk versi GUI

/*

 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license

 * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template

 */

package calculator.gui;


/**

 *

 * @author Ahroi

 */

public class NewJFrameCal extends javax.swing.JFrame {


    /**

     * Creates new form NewJFrameCal

     */

    public NewJFrameCal() {

        initComponents();

    }


    /**

     * This method is called from within the constructor to initialize the form.

     * WARNING: Do NOT modify this code. The content of this method is always

     * regenerated by the Form Editor.

     */

    @SuppressWarnings("unchecked")

    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          

    private void initComponents() {


        jPanel4 = new javax.swing.JPanel();

        jLabel1 = new javax.swing.JLabel();

        jLabel2 = new javax.swing.JLabel();

        num1 = new javax.swing.JTextField();

        num2 = new javax.swing.JTextField();

        jPanel1 = new javax.swing.JPanel();

        add = new javax.swing.JButton();

        sub = new javax.swing.JButton();

        mul = new javax.swing.JButton();

        div = new javax.swing.JButton();

        jPanel2 = new javax.swing.JPanel();

        operasi = new javax.swing.JComboBox<>();

        counting = new javax.swing.JButton();

        jPanel5 = new javax.swing.JPanel();

        res = new javax.swing.JLabel();


        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);

        jPanel4.setLayout(jPanel4Layout);

        jPanel4Layout.setHorizontalGroup(

            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGap(0, 100, Short.MAX_VALUE)

        );

        jPanel4Layout.setVerticalGroup(

            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGap(0, 100, Short.MAX_VALUE)

        );


        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        setTitle("Simple Calculator 2 Options");

        setLocation(new java.awt.Point(400, 300));

        setResizable(false);


        jLabel1.setText("Number 1");


        jLabel2.setText("Number 2");


        num1.addKeyListener(new java.awt.event.KeyAdapter() {

            public void keyReleased(java.awt.event.KeyEvent evt) {

                num1KeyReleased(evt);

            }

        });


        jPanel1.setBackground(new java.awt.Color(0, 204, 204));


        add.setText("+");

        add.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                addActionPerformed(evt);

            }

        });


        sub.setText("-");

        sub.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                subActionPerformed(evt);

            }

        });


        mul.setText("*");

        mul.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                mulActionPerformed(evt);

            }

        });


        div.setText("/");

        div.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                divActionPerformed(evt);

            }

        });


        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

        jPanel1.setLayout(jPanel1Layout);

        jPanel1Layout.setHorizontalGroup(

            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(jPanel1Layout.createSequentialGroup()

                .addContainerGap()

                .addComponent(add)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addComponent(sub)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

                .addComponent(mul)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addComponent(div)

                .addContainerGap())

        );

        jPanel1Layout.setVerticalGroup(

            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(jPanel1Layout.createSequentialGroup()

                .addContainerGap()

                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(add)

                    .addComponent(sub)

                    .addComponent(mul)

                    .addComponent(div))

                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

        );


        jPanel2.setBackground(new java.awt.Color(153, 255, 255));


        operasi.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Add", "Sub", "Mul", "Div" }));


        counting.setText("COUNT");

        counting.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                countingActionPerformed(evt);

            }

        });


        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);

        jPanel2.setLayout(jPanel2Layout);

        jPanel2Layout.setHorizontalGroup(

            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(jPanel2Layout.createSequentialGroup()

                .addContainerGap()

                .addComponent(operasi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addComponent(counting, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

        );

        jPanel2Layout.setVerticalGroup(

            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(jPanel2Layout.createSequentialGroup()

                .addContainerGap()

                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(operasi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                    .addComponent(counting))

                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

        );


        res.setFont(new java.awt.Font("Segoe UI", 1, 48)); // NOI18N

        res.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        res.setText(" ");

        res.setAlignmentY(0.0F);

        res.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        res.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);


        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);

        jPanel5.setLayout(jPanel5Layout);

        jPanel5Layout.setHorizontalGroup(

            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addComponent(res, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

        );

        jPanel5Layout.setVerticalGroup(

            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addComponent(res, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)

        );


        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

        getContentPane().setLayout(layout);

        layout.setHorizontalGroup(

            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(layout.createSequentialGroup()

                .addContainerGap()

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

                    .addGroup(layout.createSequentialGroup()

                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                            .addComponent(jLabel1)

                            .addComponent(num1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))

                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                            .addComponent(num2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)

                            .addComponent(jLabel2)))

                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()

                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))

                .addContainerGap())

        );

        layout.setVerticalGroup(

            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(layout.createSequentialGroup()

                .addContainerGap()

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(jLabel1)

                    .addComponent(jLabel2))

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(num1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                    .addComponent(num2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

                .addGap(18, 18, 18)

                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

        );


        pack();

    }// </editor-fold>                        


    private void countingActionPerformed(java.awt.event.ActionEvent evt) {                                         

        if (operasi.getSelectedItem().toString().equalsIgnoreCase("Add")){

            int a=Integer.parseInt(num1.getText());

            int b=Integer.parseInt(num2.getText());

            int counting=a+b;

            res.setText (Integer.toString (counting));   

        }

        if (operasi.getSelectedItem().toString().equalsIgnoreCase("Sub")){

            int a=Integer.parseInt(num1.getText());

            int b=Integer.parseInt(num2.getText());

            int counting=a-b;

            res.setText (Integer.toString (counting));   

        }

        if (operasi.getSelectedItem().toString().equalsIgnoreCase("Mul")){

            int a=Integer.parseInt(num1.getText());

            int b=Integer.parseInt(num2.getText());

            int counting=a*b;

            res.setText (Integer.toString (counting));   

        }

        if (operasi.getSelectedItem().toString().equalsIgnoreCase("Div")){

            int a=Integer.parseInt(num1.getText());

            int b=Integer.parseInt(num2.getText());

            int counting=a/b;

            res.setText (Integer.toString (counting));   

        }        

    }                                        


    private void addActionPerformed(java.awt.event.ActionEvent evt) {                                    

        int a=Integer.parseInt(num1.getText());

        int b=Integer.parseInt(num2.getText());

        int counting=a+b;

        res.setText (Integer.toString (counting));

    }                                   


    private void subActionPerformed(java.awt.event.ActionEvent evt) {                                    

        int a=Integer.parseInt(num1.getText());

        int b=Integer.parseInt(num2.getText());

        int counting=a-b;

        res.setText (Integer.toString (counting));

    }                                   


    private void mulActionPerformed(java.awt.event.ActionEvent evt) {                                    

        int a=Integer.parseInt(num1.getText());

        int b=Integer.parseInt(num2.getText());

        int counting=a*b;

        res.setText (Integer.toString (counting));

    }                                   


    private void divActionPerformed(java.awt.event.ActionEvent evt) {                                    

        int a=Integer.parseInt(num1.getText());

        int b=Integer.parseInt(num2.getText());

        int counting=a/b;

        res.setText (Integer.toString (counting));

    }                                   


    /**

     * @param args the command line arguments

     */

    public static void main(String args[]) {

        /* Set the Nimbus look and feel */

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 

         */

        try {

            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {

                if ("Nimbus".equals(info.getName())) {

                    javax.swing.UIManager.setLookAndFeel(info.getClassName());

                    break;

                }

            }

        } catch (ClassNotFoundException ex) {

            java.util.logging.Logger.getLogger(NewJFrameCal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {

            java.util.logging.Logger.getLogger(NewJFrameCal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {

            java.util.logging.Logger.getLogger(NewJFrameCal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (javax.swing.UnsupportedLookAndFeelException ex) {

            java.util.logging.Logger.getLogger(NewJFrameCal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        }

        //</editor-fold>


        /* Create and display the form */

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                new NewJFrameCal().setVisible(true);

            }

        });

    }


    // Variables declaration - do not modify                     

    private javax.swing.JButton add;

    private javax.swing.JButton counting;

    private javax.swing.JButton div;

    private javax.swing.JLabel jLabel1;

    private javax.swing.JLabel jLabel2;

    private javax.swing.JPanel jPanel1;

    private javax.swing.JPanel jPanel2;

    private javax.swing.JPanel jPanel4;

    private javax.swing.JPanel jPanel5;

    private javax.swing.JButton mul;

    private javax.swing.JTextField num1;

    private javax.swing.JTextField num2;

    private javax.swing.JComboBox<String> operasi;

    private javax.swing.JLabel res;

    private javax.swing.JButton sub;

    // End of variables declaration                   

}



Untuk lebih memahaminya silahkan kunjungi Youtube


No comments:

Post a Comment