Possible Duplicate:
Find the max of 3 numbers in Java with different data types (Basic Java)
Write a program that uses a scanner to read three integers (positive) displays the biggest number of three. (Please complete without using either of the operators &&
or ||
. These operators will be covered in class shortly. Similarly loops are not required.)
Some sample run:
Please input 3 integers: 5 8 3
The max of three is: 8
Please input 3 integers: 5 3 1
The max of three is 5
import java.lang.Math;
import java.util.Scanner;
public class max {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please input 3 integers: ");
String x = keyboard.nextLine();
String y = keyboard.nextLine();
String z = keyboard.nextLine();
int max = Math.max(x,y,z);
System.out.println(x + " " + y + " "+z);
System.out.println("The max of three is: " + max);
}
}
I want to know what's wrong with this code and how I can find the max when I input 3 different values.
First, the three numbers are defined. If num1 is greater than num2 and num3, then it is the maximum number. If num2 is greater than num1 and num3, it is the maximum number. Otherwise, num3 is the maximum number.
max only takes two arguments. If you want the maximum of three, use Math.
max() function is an inbuilt function in Java which returns maximum of two numbers. The arguments are taken in int, double, float and long.
Two things: Change the variables x
, y
, z
as int
and call the method as Math.max(Math.max(x,y),z)
as it accepts two parameters only.
In Summary, change below:
String x = keyboard.nextLine();
String y = keyboard.nextLine();
String z = keyboard.nextLine();
int max = Math.max(x,y,z);
to
int x = keyboard.nextInt();
int y = keyboard.nextInt();
int z = keyboard.nextInt();
int max = Math.max(Math.max(x,y),z);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With