Smallest and largest integers using if / else only

Here is my code to display the smallest and largest integer, taking 5 inputs from the user ... it works for smallest values, but not for large ones, and I can't figure out the problem ... please help

import java.util.Scanner;

public class LargestAndSmallestIntegers {

    public static void main(String[] args) {


        Scanner input=new Scanner(System.in);
        int a,b,c,d,e;
        int small,large;

        System.out.println("Enter five integer values...");



        a=input.nextInt();

        small=a;
        large=a;

        b=input.nextInt();

        if (small<b)
        {
            large=b;
        }

        else 
        {
            small=b;
        }
        c=input.nextInt();

        if  (small<c)
        {
            large=c;
        }

        else
        {
            small=c;
        }

        d=input.nextInt();
        if (small<d)
        {
            large=d;
        }

        else
        {
            small=d;
        }
        e=input.nextInt();
        if (small<e)
        {
            large=e;
        }

        else
        {
            small=e;
        }


        input.close();  
         System.out.printf("%d is smallest and %d is largest", small,large);        

    }   
}

      

-2


source to share


3 answers


private int a = input.nextInt(),
    b = input.nextInt(),
    c = input.nextInt(),
    d = input.nextInt(),
    e = input.nextInt();

private int small, large;

small = min(a,b);
small = min(small,c);
small = min(small,d);
small = min(small,e);

large = max(a,b);
large = max(large,c);
large = max(large,d);
large = max(large,e);

private int min(int a, int b) {
    if (a < b) return a else return b;
}

private int max(int a, int b) {
    if (a > b) return a else return b;
}

      



I think it works;)

+1


source


it works for smallest values, but not largest

As lared indicated that the comparison with small

to determine large

is erroneous. You should include something like this in your comparison logic:

    if (large < b)
    {
        large = b;
    }

      



in addition to the existing comparison:

    if (small > b)
    {
        small = b;
    }

      

0


source


you are always just checking for the smallest value. you also need to check

if (small<e)
        {
            if(large < e)
              {
                  large=e;
               }
        }

      

-1


source







All Articles