简体   繁体   中英

Java if-statement homework

I have homework that requires me to find the 2 largest of 4 input numbers.

I tried an if statement, but I think I am going about it the wrong way. I must use if statements or while loops. How do I continue?

if ((a>b && b>c && c>d)||(a>b && b>d && d>c)){
    System.out.println("max1 is : " + a);
    System.out.println("max2 is : " + b);}   
else  if ((b>a && a>c && c>d)||(b>a && a>c && d>c) ){
    System.out.println("max1 is : " + b);
    System.out.println("max2 is : " + a);}
 if ((c>a && a>b && b>d)||(c>a && a>b && d>b)){
    System.out.println("max1 is : " + c);
    System.out.println("max2 is : " + a);}

Using java primitive array:

int[] num = {a, b, c, d};

Arrays.sort(num);

System.out.println("Largest is : " + num[3]);
System.out.println("Second Largest is : " + num[2]);

// largest two numbers will occupy the last two positions 3 & 2 in the array.

just put the parameters in an array, sort that array and display the last elements

 public static void main(String[] args) {
        dispayMax(5,  -13, 7, 88);
    }

    public static void dispayMax(int a, int b, int c, int d){
        int[] array = {a, b, c, d};
        Arrays.sort(array);
        int length = array.length;
        System.out.println("max1 is : " + array[length -2]);
        System.out.println("max2 is : " + array[length -1]);
}

You can use a collection to avoid to write such <,> conditions multiple times. A collection or array can come handy in this case.

min1- smallest number, min2 - second smallest. Their initial value is set to be the maximum integer value possible
In the for loop, for every element, if the element is smaller than the min1 value, assign the current min1 value to min2 and set min1 as the element itself. If the elements value is smaller than min2 but not min1, assign its value to min2, min1 remains unchanged.

One of the way to use it is. :

int min1 = Integer.MAX_VALUE, min2 =Integer.MAX_VALUE;

        int[] arr = {a,b,c,d}; // created an array with the four elements
        for(int i=0;i<arr.length;i++) {
            if(min1>arr[i]) { //array is minimising the checks to be written 
                min2=min1;
                min1=arr[i];
            }else if(min2>arr[i]) {
                min2=arr[i];
            }
        }
import java.util.Arrays;

public class Homework{

     public static void main(String []args){

        int myArray[] = {4, 10, 1, 100}; //insert your 4 numbers

        Arrays.sort(myArray);

        System.out.println("The max is: " + myArray[3]);
        System.out.println("The 2nd max is: " + myArray[2]);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM