Java 常见例子

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

方法一:使用If语句

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

public class MyClass {
  static void largest(int x, int y, int z) {
    int max = x;

    if (x >= y && x >= z)
      max = x;
    if (y >= x && y >= z)
      max = y;
    if (z >= x && z >= y)
      max = z;
    System.out.println("largest number among " + x + ", " + 
                        y + " and " + z + " is: " + max);
  }

  public static void main(String[] args) {
    largest(100, 50, 25);
    largest(50, 50, 25);
  }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

上面的代码将输出如下:

largest number among 100 , 50 and 25 is:  100
largest number among 50 , 50 and 25 is:  50 
  • 1

方法二:使用If-else语句

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

public class MyClass {
  static void largest(int x, int y, int z) {
    int max = x;

    if (x >= y && x >= z)
      max = x;
    else if (y >= x && y >= z)
      max = y;
    else 
      max = z;

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

  public static void main(String[] args) {
    largest(100, 50, 25);
    largest(50, 50, 25);
  }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

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

largest number among 100 , 50 and 25 is:  100
largest number among 50 , 50 and 25 is:  50 
  • 1

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

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

public class MyClass {
  static void largest(int x, int y, int z) {
    int max = x;
    
    if (x >= y) {
      if(x >= z) 
        max = x;
      else
        max = z;
    }
    else {
      if(y >= z) 
        max = y;
      else
        max = z;
    }
    
    System.out.println("largest number among " + x + ", " + 
                        y + " and " + z + " is: " + max);
  }

  public static void main(String[] args) {
    largest(100, 50, 25);
    largest(50, 50, 25);
  }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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

largest number among 100 , 50 and 25 is:  100
largest number among 50 , 50 and 25 is:  50 
  • 1

方法 4:使用三元运算符

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

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

  public static void main(String[] args) {
    largest(100, 50, 25);
    largest(50, 50, 25);
  }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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

largest number among 100 , 50 and 25 is:  100
largest number among 50 , 50 and 25 is:  50 
  • 1