/* DeleteCommandLine.java -- Array example program
by Craig Persiko for CS 111A
Reads from command line a series of numbers into an array, then deletes the one specified by the user
*/
import java.util.Scanner;
class DeleteCommandLine
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] nums; // array reference variable
int i, numEntries, numToDelete;
// Make sure user entered at least one command line argument:
if(args == null || args.length < 1)
{
System.out.println("usage: java DeleteCommandLine 5 4 2 8\nTo delete one of the numbers 5, 4, 2 and 8");
return;
}
numEntries = args.length;
nums = new int[numEntries];
// convert command line into integers, and put into nums array.
for(i=0; i < numEntries; i++)
nums[i] = Integer.parseInt(args[i]);
// now nums array is filled with numbers from command line
System.out.println("Here is your array of numbers:");
outputArray(nums, numEntries);
System.out.print("Which number do you want to remove? ");
numToDelete = scan.nextInt();
for(i=0; i < numEntries; i++)
if(nums[i] == numToDelete)
{
deleteFromArray(nums, i); // delete element number i from the array
numEntries--; // now we have one fewer element to output
// in case there is another copy of numToDelete in the array, we'll keep looping.
// since we just moved the following element back to element i, we need to check i again.
i--;
}
System.out.println("Here is the array with " + numToDelete + " removed:");
outputArray(nums, numEntries);
}
// output the array, separated by commas:
public static void outputArray(int[] nums, int numElements)
{
System.out.print(nums[0]); // output first value
// output rest of array with commas:
for (int i = 1; i < numElements; i++)
System.out.print(", " + nums[i]);
System.out.println();
}
// remove element indexToDelete from the array a
public static void deleteFromArray(int[] a, int indexToDelete)
{
for(int i=indexToDelete; i < a.length-1; i++)
a[i] = a[i+1];
}
}
/* Sample Output:
[cpersiko@fog cs111a]$ javac DeleteCommandLine.java
[cpersiko@fog cs111a]$ java DeleteCommandLine
usage: java DeleteCommandLine 5 4 2 8
To delete one of the numbers 5, 4, 2 and 8
[cpersiko@fog cs111a]$ java DeleteCommandLine 1 2 3 8 9 10
Here is your array of numbers:
1, 2, 3, 8, 9, 10
Which number do you want to remove? 2
Here is the array with 2 removed:
1, 3, 8, 9, 10
[cpersiko@fog cs111a]$ java DeleteCommandLine 1 2 3 8 9 10 3 3 5 6
Here is your array of numbers:
1, 2, 3, 8, 9, 10, 3, 3, 5, 6
Which number do you want to remove? 3
Here is the array with 3 removed:
1, 2, 8, 9, 10, 5, 6
[cpersiko@fog cs111a]$
*/
syntax highlighted by Code2HTML, v. 0.9