Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to find a max of three numbers in java [duplicate]

Tags:

java

max

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.

like image 729
user1730357 Avatar asked Oct 09 '12 04:10

user1730357


People also ask

How do you find the maximum of 3 numbers using Java Max?

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.

Can Math Max take 3 parameters?

max only takes two arguments. If you want the maximum of three, use Math.

Is there MAX function in Java?

max() function is an inbuilt function in Java which returns maximum of two numbers. The arguments are taken in int, double, float and long.


1 Answers

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);
like image 64
Yogendra Singh Avatar answered Oct 08 '22 23:10

Yogendra Singh