Java
Write a recursive boolean method named isMember. The method
should accept two
arguments: an int array and an int value. The method should return
true
if the value is found in the array, or false if the value is not
found in
the array.
Demonstrate the method in a program that takes input from the user.
First,
the program should prompt the user to enter the length of the
array. Then,
it should prompt the user for every member of the array. Then, it
should ask
the user for a number to search for in the array, and print whether
the
number is a member of the array (either "true" or "false").
import java.util.Scanner; public class Member { public static boolean isMember(int[] arr, int n) { return isMember(arr, n, 0); } public static boolean isMember(int[] arr, int n, int index) { if (index < arr.length) { return arr[index] == n || isMember(arr, n, index+1); } else { return false; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("How many numbers in array: "); int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { System.out.print("Enter a number: "); arr[i] = in.nextInt(); } System.out.print("Enter a number to search for: "); int num = in.nextInt(); System.out.println(isMember(arr, num)); } }
Get Answers For Free
Most questions answered within 1 hours.