Java 常见例子

给定三个数字xyz,可以使用以下方法找出这三个数字中最小的数字。

方法一:使用If语句

下面的例子中,只使用了if条件语句。

public class MyClass {
  static void smallest(int x, int y, int z) {
    int min = x;

    if (x <= y && x <= z)
      min = x;
    if (y <= x && y <= z)
      min = y;
    if (z <= x && z <= y)
      min = z;

    System.out.println("Smallest number among " + x + ", " + 
                        y + " and " + z + " is: " + min);
  }

  public static void main(String[] args) {
    smallest(100, 50, 25);
    smallest(50, 50, 25);
  }
} 

上面的代码将输出如下:

Smallest number among 100 , 50 and 25 is:  25
Smallest number among 50 , 50 and 25 is:  25 

方法二:使用If-else语句

也可以使用If-else条件语句来解决.

public class MyClass {
  static void smallest(int x, int y, int z) {
    int min = x;

    if (x <= y && x <= z)
      min = x;
    else if (y <= x && y <= z)
      min = y;
    else 
      min = z;

    System.out.println("Smallest number among " + x + ", " + 
                        y + " and " + z + " is: " + min);
  }

  public static void main(String[] args) {
    smallest(100, 50, 25);
    smallest(50, 50, 25);
  }
} 

上面的代码将给出以下输出:

Smallest number among 100 , 50 and 25 is:  25
Smallest number among 50 , 50 and 25 is:  25 

方法3:使用嵌套的If-else语句

上面的问题可以也可以使用嵌套的 if-else 条件语句来解决。

public class MyClass {
  static void smallest(int x, int y, int z) {
    int min = x;

    if (x <= y) {
      if(x <= z) 
        min = x;
      else
        min = z;
    }
    else {
      if(y <= z) 
        min = y;
      else
        min = z;
    }

    System.out.println("Smallest number among " + x + ", " + 
                        y + " and " + z + " is: " + min);
  }

  public static void main(String[] args) {
    smallest(100, 50, 25);
    smallest(50, 50, 25);
  }
} 

上面的代码将给出以下输出:

Smallest number among 100 , 50 and 25 is:  25
Smallest number among 50 , 50 and 25 is:  25 

方法 4:使用三元运算符

这里也可以使用三元运算符。

public class MyClass {
  static void smallest(int x, int y, int z) {
    int min = x;
    min = (x < y)? ((x < z)? x : z) : ((y < z)? y : z);
    System.out.println("Smallest number among " + x + ", " + 
                        y + " and " + z + " is: " + min);
  }

  public static void main(String[] args) {
    smallest(100, 50, 25);
    smallest(50, 50, 25);
  }
} 

上面的代码将给出以下输出:

Smallest number among 100 , 50 and 25 is:  25
Smallest number among 50 , 50 and 25 is:  25