Explanation of Solution
Method “lastIndexOf()” to return the last index of an array:
//Definition of class
public class Text {
//Definition of main method
public static void main(String[] args)
{
//Create an array
int[] arr = {74, 85, 102, 99, 101, 85, 56};
//Call the method lastIndexOf()
System.out.println(lastIndexOf(arr, 85));
}
//Definition of method lastIndexOf()
public static int lastIndexOf(int[] arr, int finValue)
{
//Traverse the for loop till it reaches the length of the array
for (int i = arr.length - 1; i >= 0; i--)
{
//Check whether a[i] equals to target
if (arr[i] == finValue)
{
//Return the value of i
return i;
}
}
//Return the value of -1
return -1;
}
}
Explanation:
- Definition of method “lastIndexOf()”.
- Traverse the “for” loop until it reaches the length.
- Check whether “a[i] ”to “finValue”
- Return the value of “i”.
- Return “-1”.
- Check whether “a[i] ”to “finValue”
- Traverse the “for” loop until it reaches the length.
Output:
5
Want to see more full solutions like this?
Chapter 7 Solutions
Building Java Programs: A Back To Basics Approach (5th Edition)
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education