Home > Enterprise >  Finding the minimum of scanner input in a method
Finding the minimum of scanner input in a method

Time:11-14

I am trying to find the minimum of a variable input of the scanner class. I have as many inputs as the user wants but I cannot seem to find out how to find the minimum of multiple inputs. Any help would be appreciated.

public static void minimum(int count)
    {
        double input;
        boolean lessThan;
        double lesser = 0;
        for(count = count; count > 0; count--)
        {
            System.out.print("Enter a double: ");
            input = console.nextDouble();
            lessThan = input < input;
            if(lessThan = true)
            {
                lesser = input;
            }
            else
            {
                lesser = input;
            }

        }
        System.out.println("The minimum is "   lesser);


    }

CodePudding user response:

Here is the answer but my answer is a little bit different. Firstly I created an initialized array because we need to execute the code several times, then I stored the user inputs into the array after that I found the min value using array indexes.

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double arr[] = new double[5];

        for (int i = 0; i < arr.length; i  ) {
            System.out.println("Enter the double");
            arr[i] = scanner.nextDouble();
        }
        double min = arr[0];
        for (int j=0;j<arr.length;j  ){
            if(arr[j]<min)
                min=arr[j];
        }
        System.out.println("min value is" " " min);
    }

CodePudding user response:

public static void main(String [] args){
    Scanner scanner = new Scanner(System.in);
    
    System.out.println("How many inputs?: ");
    int answer = scanner.nextInt();
    int arr[] = new int[answer];
    int y = 0;
    
    while(y < answer){
        System.out.println("Enter a value: ");
        arr[y] = scanner.nextInt();
        
        y  ;
    }
    int smallNum = arr[arr.length - 1];
    for(int i = arr.length; i > 0; i--){
        if(smallNum > arr[i - 1]){
            smallNum = arr[i - 1];
        }
    }
     System.out.println("Minimum is: "   smallNum);
}
  • Related