How to end loop when user inputs "exit" when asked for name?

Ibrahim :

When the program prints "Please enter your name: ", if the user enters exit, the program should end.

BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

String input = "";

while(true) {
    System.out.println("Please enter your name: ");
    input = User_Input.next();
    bufferedWriter.write("Name: " + input);
    System.out.println("Please enter your address: ");
    input = User_Input.next();
    bufferedWriter.write(", Address: " + input);
    System.out.println("Please enter your phone no: ");
    input = User_Input.next();
    bufferedWriter.write(", Phone: " + input);
    bufferedWriter.newLine();
}
bufferedWriter.close();
fantaghirocco :

In any kind of loop

  • break can be used to exit the loop
  • continue causes the loop to continue with the next iteration
  • return breaks the loop and causes the container method to exit by giving the control back to the caller

In your case you can test if the condition is met like this:

input = User_Input.next();
if ("exit".equals(input))
    break;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=389068&siteId=1