可以找到5个数字中最大的代码

时间:2016-11-21 21:23:28

标签: java

我是新来的 我必须编写一个代码,可以找到放置用户的5个数字中最大的一个。我写了一些东西,但它没有用。谁能帮我?谢谢!

public static void main(String[] args) {
    // import java.lang.Math;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please input 5 integers: ");
    int x = Integer.parseInt(keyboard.nextLine());
    int y = Integer.parseInt(keyboard.nextLine());
    int z = Integer.parseInt(keyboard.nextLine());
    int m = Integer.parseInt(keyboard.nextLine()); 
    int n = Integer.parseInt(keyboard.nextLine()); 
    int max = Math.max(x,y);

    if (x>y && x>z && x>m && x>n)
        System.out.println ("The first of your numbers is the bigest");

    else if(y>x && y>z && y>m && y>n)
        System.out.println ("The second of your numbers is the bigest");

    else if (z>x && z>y && z>m && z>n)
         System.out.println ("The third of your numbers is the bigest");

    else if (m>x && m>y && m>z && m>n)
         System.out.println ("The fourth of your numbers is the bigest");

    else if (n>x && n>y && n>z && n>m)
         System.out.println ("The fifth of your numbers is the bigest");




    System.out.println("The max of three is: " + max); 

4 个答案:

答案 0 :(得分:2)

Collections课为你做:)

List<Integer> list = Arrays.asList(x,y,z,m,n);
int max = Collections.max(list).intValue();
System.out.println("And the winner is: " + max);

如果您想在集合中找到该位置,您应该按照以下步骤进行操作:

int index = list.indexOf(max);
String[]position={"first","second","third","fourth","fifth"};
System.out.println("The "+position[index]+" of your numbers is the bigest");

答案 1 :(得分:0)

您只找到x和y的最大值并最后打印出来。您应该在每个条件中为max指定新值(在if - else if语句中)。例如,在第一个条件下,如果x大于y,z,m和n,则应将x指定为max。

答案 2 :(得分:0)

虽然这可以通过Collections.max()来回答,但这看起来像家庭作业,它可能正在寻找一种更为疯狂的方法,例如....

int [] array = {x, y, z, m , n};

int largest = x;
int index = 0;
for (int i = 0; i < array.length; i++) {
    if (array[i] > largest) {
        largest = array[i];
        index = i;
    }
}
System.out.println("Largest found at index " + index);

答案 3 :(得分:0)

我看到您使用了Math.max(),这意味着您可以使用它,并且您可以充分利用它。如果您不能使用数组或其他数据结构,您可以考虑这一点:

要获得5个数字的最大值,您可以这样做:

int largest = Math.max(Math.max (Math.max(x,y), Math.max(m,n)), z);

打印最大的位置:

String pos = "";
switch(largest){
    case x: pos = "first";
            break;
    case y: pos = "second";
            break;
    case z: pos = "third";
            break;
    case m: pos = "forth";
            break;
    case n: pos = "fifth";
            break;
};

System.out.println ("The " + pos " + of your numbers is the biggest");