TheLegend
TheLegend

Reputation: 35

minimum of integers

package variousprograms;
import java.util.*;
public class InputStats 
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int a;
        int b;
        int c;
        int d;
        int e;

        System.out.println("First Integer ");
        a = input.nextInt();
        System.out.println("Second Integer ");
        b = input.nextInt();
        System.out.println("Third Integer ");
        c = input.nextInt();
        System.out.println("Fourth Integer ");
        d = input.nextInt();
        System.out.println("Fifth Integer ");
        e = input.nextInt();

        System.out.println("Maximum is " + Math.max(Math.max(Math.max(Math.max(a,b), c), d), e));
        System.out.println("Minimum is " + Math.min(Math.min(Math.min(Math.min(a,b), c), d), e));
        System.out.println("Mean is " + (a + b + c + d + e)/5.0);    
    }
}

I wrote this code to find the minimum, maximum, and mean of a set of five integers using five variables for each integer. The problem is that I am supposed to use four variables instead of five, and I cannot use control statements such as if or loop.

How should I change the code I already wrote?

Upvotes: 1

Views: 1462

Answers (2)

Jason
Jason

Reputation: 11822

You don't need to store the inputs any longer than necessary, just store the results as you go:

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    int min;
    int max;
    long total;
    int val;

    System.out.println("First Integer ");
    val = input.nextInt();
    min = val;
    max = val;
    total = val;

    System.out.println("Second Integer ");
    val = input.nextInt();
    min = Math.min(val, min);
    max = Math.max(val, max);
    total += val;

    System.out.println("Third Integer ");
    val = input.nextInt();
    min = Math.min(val, min);
    max = Math.max(val, max);
    total += val;

    System.out.println("Fourth Integer ");
    val = input.nextInt();
    min = Math.min(val, min);
    max = Math.max(val, max);
    total += val;

    System.out.println("Fifth Integer ");
    val = input.nextInt();
    min = Math.min(val, min);
    max = Math.max(val, max);
    total += val;

    System.out.println("Maximum is " + max);
    System.out.println("Minimum is " + min);
    System.out.println("Mean is " + total / 5.0);
}

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 406125

You could do it with variables for the current input, min, max, and total. Just keep re-using the same variable for input, and update the other three variables before you get the next input from the user.

To keep track of the maximum value without if statements, you'll have to do something like:

max = Math.max(max, input);

And something similar for the minimum value.

Upvotes: 1

Related Questions