Hi guys, I'm new to Java and was wondering if you could help with one little problem with my code.

System.out.print("Enter title: ");
        String title = keyboard.next();
        if (title.equals("Mrs") || title.equals("Miss") || title.equals("Mr") || title.equals("Ms")) 
        {
            title = title;
        }
        else 
        {
            System.out.println("Enter a valid title");
        }

If the title entered is different from the acceptable values, the error message pops up. How can I add a method (after System.out.println) which does not allow you to go any further until a valid value is entered, because at the moment even if I enter an invalid value the message appears but the title is set to that invalid value. I'm testing this using a TextUI.

Thanks in advance

Edited 5 Years Ago by DoubleGee: n/a

Wrap the questioning part in a "while" loop.

Thanks for the quick reply.. but isn't there a simpler way, because I'm not allowed to use loops.

Edited 5 Years Ago by DoubleGee: n/a

The word "until" suggests looping.
Here is a simple example:

import java.util.Scanner;

public class DW_391071
{
	public static void main(String[] args)
	{
		boolean blnAcceptable = false;
		Scanner keyboard = new Scanner(System.in);

		while(!blnAcceptable)
		{
			System.out.print("Enter title: ");
			String title = keyboard.next();
			if (title.equals("Mrs") || title.equals("Miss") || title.equals("Mr") || title.equals("Ms"))
			{
				title = title;
				blnAcceptable = true;
			}
			else
			{
				System.out.println("Enter a valid title");
        	}
		}
	}
}

If you are not allowed to do even that, you could repeat your lines of code the number of times you would allow the user to enter a valid title.

Also, something like looping is the single greatest benefit of high-level languages.

Edited 5 Years Ago by thines01: clarity

This question has already been answered. Start a new discussion instead.