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

Recommended Answers

All 3 Replies

Wrap the questioning part in a "while" loop.

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.