问题
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