Print the largest number in a given number – Java… here is a solution to the problem.
Print the largest number in a given number – Java
First of all, I apologize if my question is not very clear.
I want the output to be the maximum possible number of user input. Example:
input: x = 0; y = 9; z = 5;
output: 950
I tried code like the one below.
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 prints something like: The seconde number is largest
. This is the correct way I define conditional statements. But how to get 950
as the end result? I know some logic is needed here, but my brain can’t seem to produce it.
Thanks for your help.
Solution
You can do this to print the numbers sequentially:
// 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]);
}