In: Computer Science
java/ netbeans
Write a recursive method smallestNumber which takes an ArrayList of Integers as input and returns the smallest number in the array. You can use a helper method if needed. Write a main method that asks the user for a series of numbers, until the user enters a period. Main should create an ArrayList of these Integers and call smallestNumber to find the smallest number and print it. Compile and test your code in NetBeans and then on Hackerrank.
Java code smallestNumber method and driver main method:
package smallestnumber;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
// this method returns the smallest number in the range starting from index up to the end of the list
public static int smallestNumber(ArrayList<Integer> list , int index)
{
// declair number at current index as minimum
int minimum = list.get(index);
// if index is not the last element's index then find the minimum value in range [index+1 , list.size()-1]
if(index < list.size()-1)
{
minimum = Math.min(minimum, smallestNumber(list,index+1));
}
// return the minimum
return minimum;
}
public static void main(String[] args) {
// list contains all the input integers
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
//input string take the input as string for all inputs
String input="";
// while loop breaks when period '.' is entered
while(true)
{
// take the input as string
System.out.print("enter a number : ");
input = in.nextLine();
// if input is period then break the while loop
if(input.equals("."))break;
//if input is not period then change it to Integer and add to list
list.add(Integer.parseInt(input));
}
// call smallestNumber method to find smallest number in list
// pass list and starting index to the method which is zero initially
System.out.println("smallest number is : "+ smallestNumber(list , 0));
}
}
Code in Netbeans IDE :
Test Run: