0
import java.util.Scanner;
public class Box
{
    public static void main(String[] args)
    {
        String empty = "";
        String yes = "yes";
        String no = "no";
        String response;
        String name;
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter your name >>");
        name = input.nextLine();
        if(name.equals(empty))
        {
            System.out.println("You did not enter a name, please try again >>");
            name = input.nextLine();
        }
        System.out.println("Would you like the profanity filter turned on?");
        response = input.nextLine();
        response = response.toLowerCase();
        if(response.equals(yes) || response.equals(no))
        {
            if(response.equals(yes))
                System.out.print("Profanity filter will be turned on.");
            else
                System.out.print("Profanity filter will not be turned on.");
        }
        else
            System.out.print("Invalid response, please try again.");
    }
}

This displays "Please enter your name >>", but no matter what I enter there, even if it's empty, it always asks if you'd like the profanity filter turned on. It just skips over the if that's supposed to loop forever until you actually enter a name, and I can't figure out why.

Also, I know I didn't ask this in the title, but I also can't figure out a way for the final statement to loop back to the "response = input.nextLine();" when someone doesn't enter either "yes" or "no".

Kat
  • 7
  • `System.out.println("Would you like the profanity filter turned on?");` is **not** inside some if so yeah you get that whatever you do. Maybe you want some while loop for the name check –  May 14 '17 at 21:13

1 Answers1

1

If you want it to loop forever then you need to use while loop and not if, e.g.:

Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
String name = input.nextLine();
while(name.isEmpty()){
    System.out.println("You did not enter a name, please try again >>");
    name = input.nextLine();
}

This will keep asking the user to enter the name until he enters a non empty String.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102