Search code examples
javaloopsjava.util.scannerjoptionpane

Confirmation in JOptionPane, can I loop back to scanner?


I'm a newbie, so forgive me if I a bit slow.

If I have a confirmation dialog in JOptionPane, can loop back to scanner if user states YES? EX: in JOptionPane, if user answers YES, then I want it to loop back to asking for Power and Exp and invoke method for result - keep repeating until user confirms NO. Does that make sense?

My complete code is below.

import java.util.Scanner;
import javax.swing.JOptionPane;

 public class XtoNthPowerRecursively {

//Main method
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter base to be raised to power: ");
double Base = input.nextDouble();

System.out.print("Enter exponent to raise base to: ");
int Exp = input.nextInt();
  if (Exp < 0) {
      System.out.print("Exponent cannot be negative. Re-enter: ");
      Exp = input.nextInt();
  }

//Print Base and Exp with result
System.out.println("Base " + Base + " raised to the power " + Exp + " is " + power(Base, Exp));

//JOptionPane confirmation dialog
int n = JOptionPane.showConfirmDialog(null,"Would you like to enter another base and power?", "Confirmation",JOptionPane.YES_NO_OPTION);
  if(n == JOptionPane.YES_OPTION)
  {
      JOptionPane.showMessageDialog(null,"Let's start");
  }
  else
  {
      JOptionPane.showMessageDialog(null,"Goodbye");
  }
  }

//Calling pow method
  public static double power(double Base, int Exp) {
if (Exp < 0 ) {
    return power(Base, ++Exp)/Base;
} else if (Exp == 0) {
    return 1.0;
} else {
    return power(Base, --Exp) * Base;
}
  }
}

Solution

  • You could enclose all the code directly relating to user input (not the pow method) in a while loop, with the terminating condition being something like boolean carryOn = false.. For example,

    while (carryOn)
    {
        Do your code here.
        Show the dialog box.
        If (userInput.equalsIgnoreCase("no"))
            carryOn = false;
            System.out.println("Goodbye"); // The loop terminates.
        else if (userInput.equalsIgnoreCase("yes"))
            carryOn = true;
            // User is returned to the start of the loop to enter another number.
    }
    

    You could also enclose the if/else statements in a loop aswell to ensure that only yes and no are valid responses, and anything else causes the dialogs to appear again...

    You also need to do some work to your first block of code. You check that the user input is less than a number, and then call scanner next straight after. This means that the first number will be checked, but the second number will be accepted NO MATTER what it is..