打印出给定数字的最大数字 – Java

首先,如果我的问题不清楚,我会道歉。

我希望输出是用户输入的最大可能数。 例:

input: x = 0; y = 9; z = 5; output: 950 

我尝试过类似下面的代码。

 import java.util.Scanner; class LargestOfThreeNumbers{ public static void main(String args[]){ int x, y, z; System.out.println("Enter three integers "); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); z = in.nextInt(); if ( x > y && x > z ) System.out.println("First number is largest."); else if ( y > x && y > z ) System.out.println("Second number is largest."); else if ( z > x && z > y ) System.out.println("Third number is largest."); } } 

上面的代码将打印如下内容: The seconde number is largest 。 这与我定义条件语句的方式是正确的。 但是如何获得950作为最终结果呢? 我知道这里需要一些逻辑,但我的大脑似乎并没有产生它。

感谢您的帮助。

使用java 8 IntStream的解决方案:

  int x = 0, y = 9, z = 5; IntStream.of(x,y,z).boxed().sorted( (i1,i2) -> Integer.compare(i2, i1)).forEach( i -> System.out.print(i)); 

您可以执行以下操作以按顺序打印数字:

 // make an array of type integer int[] arrayOfInt = new int[]{x,y,z}; // use the default sort to sort the array Arrays.sort(arrayOfInt); // loop backwards since it sorts in ascending order for (int i = 2; i > -1; i--) { System.out.print(arrayOfInt[i]); } 

您可以通过连续调用Math.max(int, int)找到最大值,并通过调用Math.min(int, int)最小值。 第一个数字是max 。 最后是min 。 剩下的项可以通过添加三个项来确定,然后减去min和max(x + y + z – max – min)。 喜欢,

 int max = Math.max(Math.max(x, y), z), min = Math.min(Math.min(x, y), z); System.out.printf("%d%d%d%n", max, x + y + z - max - min, min); 

像这样的东西会起作用

  ArrayList myList = new ArrayList(); Scanner val = new Scanner(System.in); int x = 0; for (int i = 0; i < 3; i++) { System.out.println("Enter a value"); x = val.nextInt(); myList.add(x); } myList.sort(null); String answer = ""; for (int i = myList.size() - 1; i >= 0; i--) { answer += myList.get(i).toString(); } System.out.println(answer); }