Search code examples
javajoptionpane

how to use option selected by user from JOptionPane in if statement?


I want users to select one of the option from JOptionPane. Then I want to use that option in an if statement. But I am not sure how to do that? Here is my code:

import javax.swing.JOptionPane;
public class MortgageCalculator {

    public static void main(String[]args)
    {
        JOptionPane.showMessageDialog(null, "Lets calculate your mortgage",null, JOptionPane.PLAIN_MESSAGE);

        double principle = Double.parseDouble(JOptionPane.showInputDialog(null, "What is your loan amount?"));

        int years = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the lenght of your loan"));
        int n = years * 12;

        double rate = Double.parseDouble(JOptionPane.showInputDialog(null, "What is your interest rate?"));

        String[] options = new String[] {"Compound", "Simple"};

        int response = JOptionPane.showOptionDialog(null, null, "Choose your interest type", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,null, options, options[0]);

        //I want to use my selected option here. 
        if(options ==compound)
        {
            double payment = (compound(principle,years,rate))/n;

        }
        else
        {
            double payment = (simple(principle, years, rate))/n;
        }
    }

    public static double simple(double principle, int n , double interestRate)
    {
        double interest = principle * n * (interestRate/100);
        double totalLoan = principle + interest;
        return totalLoan;
    }

    public static double compound(double principle, int years, double interestRate)
    {
        int n = years * 12;
        double base = (principle* (1+ (interestRate/100)*1/n));
        double amount = Math.pow(base, n);
        return amount;
    }

Btw, this is not a complete code. There are syntax missing. Thanks for the help.


Solution

  • When your buttons are provided to the dialog in a String array then when that button is selected it is the index value to where that button name resides within the array that is returned.

    Compound would return a index value of 0 from the dialog and Simple would return a index value of 1.

    // Compound (0)
    if(response == 0) {
        double payment = (compound(principle,years,rate))/n;
    
    }
    // Simple (1)
    else {
        double payment = (simple(principle, years, rate))/n;
    }
    

    Check the value in the response variable.... Not options.