In: Computer Science
Exercise 1
Modify the List<T> class of Figure 21.3 in the textbook to include a method that recursively searches a linked-list for a specified value. Ensure that the name of your method includes your last name. The method must return a reference to the value if it is found; otherwise, it must return null. Use your method in a test program that creates a list of integers. The program must prompt the user for a value to locate in the list.
I need the code modified in java to pull out the correct input below is my code, but when ran the only out I get is "Enter integers(-1 to stop):" and nothing else
PLEASE HELP
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static <T> T search_mylastname(List<T> list, T
value, int index){//function name can be updated in all places to
the lastname if needed
if(list == null || index == list.size())
return null;
if(value.equals(list.get(index)))
return list.get(index);
return search_mylastname(list, value, index+1);
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
System.out.println("Enter integers(-1 to stop): "
+ "2, "
+ "4, "
+ "6, "
+ "8, "
+ "10");
int num;
Scanner sc = new Scanner(System.in);
while(true){
num = sc.nextInt();
if(num == -1)
break;
list.add(num);
}
System.out.print("Enter integer to search: ");
int key = sc.nextInt();
Integer res = search_mylastname(list, key, 0);
if(res == null)
System.out.println(key+" is not in list");
else
System.out.println(key+" is available in list");
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static <T> T search_mylastname(List<T> list, T
value, int index){//function name can be updated in all places to
the lastname if needed
if(list == null || index == list.size())
return null;
if(value.equals(list.get(index)))
return list.get(index);
return search_mylastname(list, value, index+1);
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
System.out.println("Enter integers(-1 to stop): "
+ "2, "
+ "4, "
+ "6, "
+ "8, "
+ "10");
int num;
Scanner sc = new Scanner(System.in);
while(true){
num = sc.nextInt();
if(num == -1)
break;
list.add(num);
}
System.out.print("Enter integer to search: ");
int key = sc.nextInt();
Integer res = search_mylastname(list, key, 0);
if(res == null)
System.out.println(key+" is not in list");
else
System.out.println(key+" is available in list");
}
}
Output:
The output when the above code is run is attached below.
Please check it.
Explanation:
When vthe program is run, the output displayed is "Enter integers(-1 to stop):2,4,6,8,10"
Then the input numbers must be entered.
The numbers entered are as follows.
2
4
6
8
10
-1
When -1 is entered, the statement "Enter integer to search: " is displayed.
Then the number 5 is entered by us.
As 5 is not in the numbers provided, it displays the result as "5 is not in list."