Learn how to find the closest number to a given number in Java using arrays, loops, and Math.abs().in this program calculates the absolute difference between each array element and the target value using the Math.abs() method.
Code Explanation (Step-by-Step)
- Create a nearestNumber() method that accepts an integer array and a target value as input.
- Initialize the index variable with 0. It stores the index of the nearest number found in the array.
- Use the Math.abs() method to calculate the absolute difference between the first array element and the target value. Store the result in the distance variable.
- Use a for loop to iterate through the remaining array elements, starting from index 1.
- Inside the loop, use Math.abs() to calculate the absolute difference between the current array element, arr[i], and the target value. Store the result in the currentDistance variable.
- If currentDistance is less than distance, assign currentDistance to distance and assign the current index i to index.
- After completing the loop, return arr[index], which is the number nearest to the target value.
- Call the nearestNumber() method from the main() method and print the returned value.
public class FindNearestNumber {
public static int nearestNumber(int[] arr, int target) {
int index = 0;
int distance = Math.abs(arr[0] - target);
for (int i = 1; i < arr.length; i++) {
int currentDistance = Math.abs(arr[i] - target);
if (currentDistance < distance) {
index = i;
distance = currentDistance;
}
}
return arr[index];
}
public static void main(String[] args) {
int[] arr = {2, 5, 6, 7, 8, 8, 9};
int target = 11;
System.out.println("Nearest Number is: " + nearestNumber(arr, target));
}
}
Output :-
Nearest Number is: 9
What Is the Nearest Number Problem in Java 8
we can sort the array based on the distance from the target and return the first element.
import java.util.Arrays;
public class FindNearestNumber {
public static int nearestNumber(int[] arr, int target) {
return Arrays.stream(arr)
.boxed()
.min((a, b) -> Integer.compare(
Math.abs(a - target),
Math.abs(b - target)))
.orElse(-1);
}
public static void main(String[] args) {
int[] arr = {2, 5, 6, 7, 8, 8, 9};
int target = 11;
System.out.println("Nearest Number is: " + nearestNumber(arr, target));
}
}
Output :-
Nearest Number is: 9
Here are some Java-related programs that will help you understand Java concepts better:
- Java Program to find First and Second Largest Array Elements
- Find the largest number in an array and a list in java 8
- Java Program to Find Third Largest Element in an Array or List
- Program to print largest and smallest element in an Array
- write a java program to find second largest element in an Array