Mehul Chachada Mehul Chachada - 2 months ago 7
Java Question

How to use String variables as a condition for looping purpose

I was trying to prepare a flow chart of program for my practice where i encounter that following situation is required for me where a user would enter a string value as input either "Yes"or "Y" and "No" or "N" and based on its input the application would either terminate or restart from a certain point till now i have this as an example in my mind

public class ApplicationName {

public static void main(String args[]) {
String restartOperation;
do {
restartOperation = Confirm_Before_Exit();
} while (!restartOperation.equals("No"));

//Rest of code
}

public static void Some_Operation() {
//Executed when called before closing application
}

public static String Confirm_Before_Exit() {
Scanner inputData = new Scanner(System.in);
String answer;
System.out.println("Do you want to perform another operation ?" + " " + "Y" + " " + "N");
answer = inputData.nextLine();
switch (answer) {
case "Y":
case "Yes":
Some_Operation();
break;
default:
System.out.println("Good Bye !");

}
return answer;
}
}


This works till the user has not given input as "No" but obviously it wont work if entered "N" or perhaps small "n" or even "no" but for timing i am only trying for "No" and "N" as input value.

Answer

change your do while to the following :

do {
        restartOperation = Confirm_Before_Exit();
} while (!restartOperation.equalsIgnoreCase("No") && !restartOperation.equalsIgnoreCase("n"));