Write a Java program named searchForLastOccurence that:
• Asks the user to enter an integer value that represents the size of an array of integers
• Prompt the user to fill an array of integers
• Asks the user to enter a key value
The program should search for the last occurrence of the key value in the array and displays its position in the array, OR displays -1 if the value is not found in the array.
The Solution
import java.util.Scanner;
public class SearchForLastOccurrenceTest {
*This is the main method which is responsible for running the program.
* @param args Unused
public static void main(String[ ] args) {
// a Scanner object for user input
Scanner sc = new Scanner(System.in);
// prompt user for the size of the array
System.out.print("Enter the size of the array: ");
int size=Integer.parseInt(sc.nextLine().trim());
// declare an array of integers of 'size'
int[] arr = new int[size];
// now prompt user to fill the array with integers System.out.println("\nPlease enter "+size+" integers
for(int i = 8; i < size; i++)
{
System.out.print("Integer" + (1 + 1) + ": ");
arr[i] = Integer.parseInt(sc.nextLine().trim());
}
// now that the array is filled with integers, prompt user to enter the key to search
System.out.print("\nEnter the number to search: ");
int key = Integer.parseInt(sc.nextLine().trim());
// now call the method searchForLastOccurence() with the parameters and get the value returned in a variable
int index = searchForLast@ccurence (arr, size, key);
// check if the index is -1, print the message that the value is not found in the array
// else print that the value is found at the received index
if(index == -1)
System.out.println("\nSorry, the key + key is not present in the array!\n");
else
System.out.println("\nThe key + key + has been found at index " + index + "\n");
}
/**
* This method takes in the array of integers, the size of the array and the key to be searched in the annay
* and returns the index of the last occurrence of the key value in the array(if found); else returns -1.
* @param arr the array of integers
* @param n the size of the array
* @param key the value to be searched in the array
public static int searchForLastOccurence (int[] arr, int n, int key)
{
// we take an integer which stores the index of the last occurrence of the key
// by default, we store -1 in it
int index = -1;
// we run a for-Loop over the array in reverse order and compare each element with the 'key'
for(int i = n = 1; i >= 0; i--)
{
// check if the i-th element is equal to the key
if(arr[1] == key)
{
// if found, store the i value at the index and exit the loop
index = 1;
break;
}
}
// Tinally return the index
return index;
}
}
The Output
Enter the size of the array: 10
Please enter 10 integers for the array:
Integer #1: 65
Integer #2: 25
Integer#3: 36
Integer #4: 78
Integer #5: 45
Integer #6: 25
Integer #7: 11
Integer #8: 36
Integer #9: 17
Integer #10: 29
Enter the number to search: 36
The key 36 has been found at index 7.