Java没有合适的方法错误:排序三个数字

时间:2015-04-19 22:02:55

标签: java java.util.scanner

我被要求编写一个测试程序,使用一种方法提示用户输入三个数字并调用一个方法以按递增顺序显示它们。随着本书使用autodidact和学习java,我还没有达到用户可能认为适合该问题的数组或其他方法的使用。但是,我一直得到临时变量可能没有被初始化和使用错误。我很感激指导代码的错误。

import java.util.Scanner;
public class Sort {
    public static void main(String[] args) {
        //create  Scanner
        Scanner s =new Scanner(System.in);
        System.out.print("Enter 3 Different numbers");
        int numb1 = s.nextInt();
        int numb2 =s.nextInt();
        int numb3 =s.nextInt();
        sort(numb1,numb2,numb3);
    }
    public  static void  sort(int x,int y, int z){
        int temp =0;
        if (y>z)
            temp =  y;
        y   = z;
        z    = temp;  
        if (x>y)
            temp  =  x;
        x    =  y;
        y    =  temp;
        if  (x>z)
            temp = x;
        x=   z ;
        z= temp;    

    System.out.println(x,y,z);
  }
}

2 个答案:

答案 0 :(得分:0)

使用int temp = 0;因为条件并非详尽无遗,即您不考虑所有情况。如果x< y< z?

答案 1 :(得分:0)

exaplain in code:

public static void sort(int x, int y, int z) {
    int temp = 0;
    //the smallest in x
    if (x > y) {
        temp = x;
        x = y;
        y = temp;
    }
    if (x > z) {
        temp = x;
        x = z;
        z = temp;
    }

    //the second smallest in y
    if (y > z) {
        temp = y;
        y = z;
        z = temp;
    }

    System.out.println(x + " " + y + " " + z);
}

此算法仅使用变量类似于冒泡排序算法