Wiring a while loop with a tracking option in java

advertisements

I am working on a loan calculator with data validation. I have written everything and good to go. The only thing I cannot figure out is how to write a while loop in where the user is asked "Continue y/n?: " and then have the program continue ONLY when the user types y/Y and the program ENDS ONLY when the user types n/N, any other input should give an error message like "Invalid, you can only enter Y or N". So if the user enters "x" it should display the error message.

I have tried else if clauses, I have also tried to validate data with the methods I used in the rest of the program but I simply don't know how to validate strings. I can only do it with primitive data types.

This is the only way i know how to write the loop as of now, the problem is it will simply end the program with anything but a Y.

an option for the assignment is to use JOptionPane but I do not know how to incorporate that into the while loop and have it display a yes and a no button.

    String choice = "y";

    while (choice.equalsIgnoreCase("y")) {

    // code here

    System.out.print("Continue? (y/n): ");
        choice = sc.next();
    }
   }


Essentially, you want two loops: one doing the work and the other one inside prompting for user validation.

boolean isContinuing = true;

while (isContinuing) {
    // do work

    boolean inputIsInvalid = true;
    while (inputIsInvalid) {
      System.out.print("Continue? (y/n): ");

      String choice = sc.next();

      if ("y".equalsIgnoreCase(choice)) {
          inputIsInvalid = false;
      }
      else if ("n".equalsIgnoreCase(choice)) {
          inputIsInvalid = false;
          isContinuing = false;
      }
      else {
          System.err.print("Error: Only valid answers are Y/N.");
      }
    }
}

Node: I am using boolean variables instead of break statements, it makes the code more straightfoward and readable.