Search code examples
javajoptionpane

Trying to reuse the code by taking series of Input using jOptionPane


I am new to jOptionPane and I am trying to achieve the following task. Please consider the following code for explanation purpose:

purchaseAmount = Double.parseDouble(JOptionPane.showInputDialog("Enter the Item Purchase Amount"));

            if(onepty.budgetAmountVerify(purchaseAmount)){

            itemNo ++;

            itemCheck = JOptionPane.showConfirmDialog(null,
                                 "Would you like to Enter More Items?", "Say Yes or No", JOptionPane.YES_NO_OPTION); 

            if (itemCheck == JOptionPane.YES_OPTION){ // For Yes JOptionPane.YES_OPTION returns 0 and for No it returns 1





             }
             else if (itemCheck == JOptionPane.NO_OPTION)s{

             }

Variable Related Information :

  • purchaseAmount is a double type variable
  • itemNo is an integet type variable
  • onepty is an object of a data definition class where budgetAmountVerify method is defined.
  • itemCheck is an Integer type variable

What I am trying to Achieve :

As soon as if condition is encountered and if the user has selected YES as his option, I would like to take the user to the same dialogbox which is defined just above the if condition, basically the following : purchaseAmount = Double.parseDouble(JOptionPane.showInputDialog("Enter the Item Purchase Amount")); . This will help me in achieving the following things:

  1. I would have to write the above piece of code again and again if user clicks on Yes option again and again.

  2. I can get a proper count of items, since after entering the if condition, I am increasing the count by 1.

Is there a way to achieve what I am looking for? Because my ultimate goal is to print the purchaseamount , itemNo value in the else condition when user doesn't clicks on No option and basically stops entering new item.


Solution

  • You can put the whole code in a do while loop. Such that if the user selects YES option the loop iterates.

    do{
            purchaseAmount = Double.parseDouble(JOptionPane.showInputDialog("Enter the Item Purchase Amount"));
    
            if(onepty.budgetAmountVerify(purchaseAmount)){
    
            itemNo ++;
    
            itemCheck = JOptionPane.showConfirmDialog(null,
                                 "Would you like to Enter More Items?", "Say Yes or No", JOptionPane.YES_NO_OPTION); 
    }
    while(itemCheck == JOptionPane.YES_OPTION)
    

    In short replace if with do while