Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help creating a program with Java code that is simple and easy to follow.

ID: 3783262 • Letter: I

Question

I need help creating a program with Java code that is simple and easy to follow. Here is the exercise:

Write a method called lastIndexOf that accepts an array of integers and an integer value as its parameters and returns the last index at which the value occurs in the array. The method should return -1 if the value is not found. For example, in the array [72, 83, 100, 97, 99, 83, 54], the last index of the value 83 is 5. The value to be searched for is entered by the user. Include a main that will call method lastIndexOf(myArray, someIndex). You may hardcode the array values when you declare the array rather than having the array contents entered from the console. Set your array size at 10 and fill your array with 10 values. Use the length property to determine the size of your array rather than hardcoding the loop invariant.

Explanation / Answer

DemoProgram.java

public class DemoProgram {

   public static void main(String[] args) {
       //Declaring and initializing the array of type integer which is of size 10
       int arr[]={72, 83, 100, 97, 99, 83, 54 , 33 ,66, 99, 109};
      
       //Calling the method by passing the inputs as arguments
       int num=lastIndexOf(arr,9);
      
       /* if the returned value is -1 then display error message
       * if not,display the number
       */
if(num==-1)
   //Displaying the error message
   System.out.println("** Value not found **");
else
   //Displaying the number present at the index
   System.out.println("The value found at index 9 in the array is "+num);
   }

   //This method will find and return the array element at an index position
   private static int lastIndexOf(int[] arr, int index) {
      
       //declaring variable
       int num = 0;
      
      
       /* This for loop will iterate over the array
       * and find the element in the array at an index position
       */
       for(int i=0;i<arr.length;i++)
       {
           if(i==index)
               num=arr[i];
       }
       return num;
   }

}

________________

Output:

The value found at index 9 in the array is 99

____________Thank You

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote