/* * Aresh Saharkhiz * saharkiz@gmail.com * Associate Professor / Mapua Institute of Technology / Philippines */ using System; using System.IO; // Introduction to Software Testing // Authors: Paul Ammann & Jeff Offutt // Chapter 1, section 1.2, page 16 internal class findLast_class { public static int findLast(int[] x, int y) { //Effects: If x==null throw NullPointerException // else return the index of the last element // in x that equals y. // If no such element exists, return -1 // As the example in the book points out, this loop should end at 0. for (int i = x.Length - 1; i > 0; i--) { if (x[i] == y) { return i; } } return -1; } // test: x=[2, 3, 5]; y = 2 // Expected = 0 public static void Main(string[] argv) { // Driver method for findLast // Read an array and an integer from standard input, call findLast() int integer = 0; int[] inArr = new int[argv.Length]; if (argv.Length == 0) { Console.WriteLine("Usage: java findLast v1 [v2] [v3] ... "); return; } for (int i = 0; i < argv.Length; i++) { try { inArr[i] = Convert.ToInt32(argv[i]); } catch (FormatException) { Console.WriteLine("Entry must be a integer, using 1."); inArr[i] = 1; } } Console.WriteLine("Enter an integer you want to find: "); integer = N; Console.WriteLine("The index of the last element equals " + integer + " is: " + findLast(inArr, integer)); } // ==================================== // Read (or choose) an integer private static int N { get { int inputInt = 1; //BufferedReader @in = new BufferedReader(new InputStreamReader(System.in)); //Console equivalent string inStr; try { inStr = Console.ReadLine(); inputInt = Convert.ToInt32(inStr); } catch (IOException) { Console.WriteLine("Could not read input, choosing 1."); } catch (FormatException) { Console.WriteLine("Entry must be a number, choosing 1."); } return (inputInt); } } // end getN }