Print largest number out of given digits - Java

梦想与她 提交于 2019-12-07 13:13:13

问题


First I would apologize if my question seems not clear.

I want output to be the largest possible number from user input. Example:

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

I tried something like the below code.

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 code above will print something like: The seconde number is largest. That is correct the way I define the conditional statements. But how do I get 950 as final result? I know some logic is required here but my brain doesn't seem to produce it.

Your help is appreciated.


回答1:


A solution using 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));



回答2:


You could do something like this to print the numbers in order:

// 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]);
}



回答3:


You can find the maximum with successive calls to Math.max(int, int) and the minimum with calls to Math.min(int, int). The first number is the max. The last is min. And the remaining term can be determined with addition of the three terms and then subtraction of the min and max (x + y + z - max - min). Like,

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);



回答4:


Something like this would work

    ArrayList<Integer> myList = new ArrayList<Integer>();
    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);
  }


来源:https://stackoverflow.com/questions/51052073/print-largest-number-out-of-given-digits-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!