chazz0153
chazz0153

Reputation: 1

Finding minimum using recursion

Ok, so I need to keep on getting the user inputs until they enter 0. I need to store them in an array and print out the minimum. But it keeps on giving me the last input number given instead of sorting and getting the minimum in the list. Here's what I've done so far.

import java.io.*;
import java.util.*;

public class FindingMin
{

    public static void main(String[] args) throws IOException
    {
        int[] Numbers = new int[100]; 
        int minimum = 0;
        int InputParser;
        String input= "1";


        try
        {
            InputStreamReader stream = new InputStreamReader (System.in);
            BufferedReader scan = new BufferedReader(stream);

            InputParser = Integer.parseInt(input);

            while(InputParser != 0)
            {
                input = scan.readLine();
                InputParser = Integer.parseInt(input);
                for(int i = 0;i<Numbers.length;i++)
                {
                    if(InputParser == 0)
                    {
                        InputParser = 0;
                    }
                    else
                    Numbers[i] = InputParser;

                }

            }

            minimum = findingMin(Numbers,Numbers[0],Numbers.length-1);
            System.out.println("The minimum number is "+minimum);


        }
        catch(NumberFormatException exception)
        {
            System.out.println("Please enter integers only");
        }

    }

    public static int findingMin(int[] list, int start, int end)
    {
           if (start == end) 
               return list[start];
           else
          {
             int Min = findingMin(list, start, end-1);
             if (Min < list[end])
                return list[end];
             else
                return Min;
           }


    }
}

Any suggestion will be greatly appreciated!

Upvotes: 0

Views: 920

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258588

That's because you have an extra loop:

while(InputParser != 0)
{
        input = scan.readLine();
        InputParser = Integer.parseInt(input);
        for(int i = 0;i<Numbers.length;i++)
        {
            if(InputParser == 0)
            {
                InputParser = 0;
            }
            else
                Numbers[i] = InputParser; // <-- you set all numbers
                                          //     to the last input here

        }

}

The correct version would be:

int i = 0;
while(InputParser != 0)
{
        input = scan.readLine();
        InputParser = Integer.parseInt(input);
        if(InputParser == 0)
        {
            InputParser = 0;
        }
        else
        {
            Numbers[i] = InputParser;
            i++;
        }
}

Also, the calling method should be:

minimum = findingMin(Numbers,0,Numbers.length-1);

not

minimum = findingMin(Numbers,Numbers[0],Numbers.length-1);

Upvotes: 2

Related Questions