对三个命令行整数进行排序

时间:2015-10-09 02:19:13

标签: java

您好我正在尝试创建一个从命令行获取三个整数的代码,并将它们分类为min,mid和max值。我无法弄清楚编程中期。它并不总是正确排序。你能帮我吗?

public class SortInteger{

public static int max3(int a, int b, int c) {
       int max = a;
       if (b > max) max = b;
       if (c > max) max = c;
       return max;
    }

public static int min3(int a, int b, int c) {
       int min = a;
       if (b < min) min = b;
       if (c < min) min = c;
       return min;}

public static int sort(int a, int b, int c){
    int sort = a;
        if (sort > b && sort < c) sort = a;
        else sort = b;
        if (sort > a && sort < c) sort = b;
        else sort =c;
        if (sort > c && sort < a) sort = c;
        else sort =b;
        if (sort > c && sort < b) sort = c;
        else sort = b;
        if (sort > a && sort < b) sort = c;
        else sort = c;
        return sort;
        }


public static void main(String[] args){
    int a= Integer.parseInt(args [0]);
    int b=Integer.parseInt(args[1]);
    int c=Integer.parseInt(args[2]);
    StdOut.println("Min is " + min3(a, b, c));
    StdOut.println("Mid is " + sort(a, b, c));
    StdOut.println("Max is " +  max3(a, b, c));


}

}

3 个答案:

答案 0 :(得分:4)

尝试:

public static int mid(int a, int b, int c){
  return a + b + c - max(a,b,c) - min(a,b,c);
}

同样适用于minmax,只需使用Math

public static int min(int a, int b, int c){
  return Math.min(Math.min(a,b),c);//Replace with Math.max for max.
}

答案 1 :(得分:1)

你在排序功能中踩着自己的脚趾。举例来说,你的前两个if语句:

if (sort > b && sort < c) sort = a;
else sort = b;
if (sort > a && sort < c) sort = b;
else sort =c;

如果a介于b和c之间,则第一个if语句将为true,sort将保留为a的值。但是,请考虑下一个。 a中的值不会大于a,因此第二个if语句将为false,并将sort更改为c,即使您已经找到a为中间值。不是你想要的。要解决此问题,您可以在if语句为true时更改执行的代码,只返回sort的值。所以,像:

if (sort > b && sort < c) return sort;
else sort = b;
if (sort > a && sort < c) return sort;
else sort =c;
// etc.

答案 2 :(得分:0)

尝试以下方法:

public class SortInteger
{
    //use general sorting algorithm for arbitrary length, this is for 3 length specifically
    public static int[] sort(int[] inputs)
    {
        int k;
        if(inputs[0] >= inputs[1])
        {
            k = inputs[0];
            inputs[0] = inputs[1];
            inputs[1] = k;
        }

        if(inputs[1] >= inputs[2])
        {
           k = inputs[1];
           inputs[1] = inputs[2];
           inputs[2] = k;
        }

        //incase our last element is less than our first we repeat:

        if(inputs[0] >= inputs[1])
        {
            k = inputs[0];
            inputs[0] = inputs[1];
            inputs[1] = k;
        }

        return inputs
    }

    public static void main(String[] args)
    {
        int[] x = new int[3];
        x[0] = Integer.parseInt(args[0]);
        x[1] = Integer.parseInt(args[1]);
        x[2] = Integer.parseInt(args[2]);
        x = sort(x);

       System.out.println("min is: " + x[0]);
       System.out.println("mid is: " + x[1]);
       System.out.println("max is: " + x[2]);
    }


}