I need to get a method in my CommonUse class to work properly with any other class. What I'm aiming for is to use this particular method in future programs for school without having to rewrite the code every time.
The purpose is to return a boolean as to whether or not to repeat a loop in another class.
CommonUse class:
// Asks if user wants to repeat something. Parameter (output) is defined by programmer when calling // this method based on the wording they want to use for the method. Example: "Would you like to // retry?" or "Would you like to play again?" public static boolean doAgain(String output) { boolean repeat = true; char response; Scanner keyboard = new Scanner(System.in); System.out.println(output); System.out.println("Y or y = Yes\nN or n = No"); response = keyboard.nextLine().charAt(0); if ((response == 'Y') || (response == 'y')) repeat = true; else if ((response == 'N') || (response == 'n')) repeat = false; else { System.out.println("Incorrect character entered. Please try again.\n"); doAgain(output); } return repeat; }
Test class:
public static void main(String[] args) { do { System.out.println("Test line\n"); } while (CommonUse.doAgain("Would you like to repeat this program?")); }
I can get the program to successfully repeat or exit with correct user input. However, if I enter a character other than a 'Y', 'y', 'N', or 'n', the doAgain() method does loop on itself again and seems to work, especially if I choose to repeat the program another time after the invalid attempt. But, if after putting, for example, a 'X', it gives the error message as usual, then repeats and asks for the correct input like I want it to. But if I enter 'N' or 'n', it repeats the program one more time, before I have to enter 'N' or 'n' again to finally exit.
It seems like there is a residual value of true for the doAgain() method when it returns to the Test class, thus making it repeat again even though the input should have made it false.
Any ideas? Thanks!