Hi all,

I have created the following code that deletes a Vector entry. Currently it gives an error if you enter a string that is not present in the Vector. Can anyone recomend a way of looping back to the original text entry point, rather than terminating the program if an incorrect entry is made??

import java.util.*;

public class Q5
{
	public static void main(String[] args)
	{
		Vector<String> staffList = new Vector<String>();
		String[] staff = {"John Smith",
						  "Sally Ann Jones",
						  "James Paul Black"};
		
		String locate;
		int Index;
		
		Scanner keyboard = new Scanner(System.in);

		for (int i=0; i<staff.length; i++)
			staffList.add(staff[i]);

		for (int i=0; i<staffList.size(); i++)
		{
			String person =
				staffList.elementAt(i); //No typecast!
			System.out.println("Staff member "
								+ (i+1) + ": " + person);
		}
		
		System.out.println("Please enter a name to be removed from the list: ");
		locate=keyboard.nextLine();
		keyboard.close();
		
		Index = staffList.indexOf(locate);
		
		if (Index >=0)
		{
			staffList.removeElementAt(Index);
			for(int i=0; i<staffList.size(); i++)
			{
				String person =
				staffList.elementAt(i);
				System.out.println("Staff member "
									+ (i+1) + ": " + person);	
			}
		}
		else
			System.out.print("Error: Please enter a valid name! ");		
	}
}

Much Apreciated.

You will need a while loop. The last for loop will not be inside that while.
You will have the while and will not exit unless a correct name is entered. If it does then exit:

int Index = -1;
String locate = "";

// so that you will enter the first time
// also note that if the name is not in the list, the indexOf returns -1
while (Index == -1) { 
   // read locate
   // get the Index.

   // if the locate (Index>=0) is found then the while will exit.
   // if it is not, the index will be -1 and you will not exit.
}

// REST OF THE CODE
staffList.removeElementAt(Index);
.....
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.