/* DeleteAllNames.java written by Craig Persiko
CS 111A Solution to in-class exercise
Gets an array of names from the command line,
inputs one name from user, and deletes that name from the list.
*/
import java.util.Scanner;
class DeleteAllNames
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String inputtedName;
boolean nameFound = false;
int numNames;
// Make sure user entered at least one command line argument:
if(args == null || args.length < 1)
{
System.out.println("usage: java SearchName Craig Bob Jane Ming:");
System.out.println("To search for a name in the list (Craig Bob Jane Ming)");
return;
}
System.out.println("Which name are you looking for?");
inputtedName = scan.nextLine();
numNames = args.length;
for(int i=0; i < numNames; )
{
if(args[i].equalsIgnoreCase(inputtedName))
{
System.out.println("Removing " + inputtedName + " from the list.");
// Starting with element i (the one to delete) Replace each element with the one that follows it:
for(int d=i; d < numNames-1; d++)
args[d] = args[d+1];
numNames--; // now we will remember that we have one fewer name, and only look at the ones which remain.
nameFound = true;
}
else
i++;
}
if(!nameFound)
System.out.println("Name not found.");
System.out.println("Here are the remaining names:");
for(int i=0; i < numNames; i++)
System.out.print(args[i] + " ");
System.out.println();
}
}
/* Sample Output:
[cpersiko@fog cs111a]$ java DeleteName Bassam Robert Ha Andy Korman Francisco Gloria
Which name are you looking for?
Robert
Removing Robert from the list.
Here are the remaining names:
Bassam Ha Andy Korman Francisco Gloria
[cpersiko@fog cs111a]$ java DeleteName Nicholas Francisco Elaine Joseph
Which name are you looking for?
Gloria
Name not found.
Here are the remaining names:
Nicholas Francisco Elaine Joseph
[cpersiko@fog cs111a]$ java DeleteName Nicholas Francisco Elaine Joseph
Which name are you looking for?
Joseph
Removing Joseph from the list.
Here are the remaining names:
Nicholas Francisco Elaine
[cpersiko@fog cs111a]$
*/
syntax highlighted by Code2HTML, v. 0.9