需要在java中找到最多三个数字 [英] Need to find a max of three numbers in java

查看:48
本文介绍了需要在java中找到最多三个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
求最大值Java 中具有不同数据类型的 3 个数字(基本 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);
    }
}   

我想知道这段代码有什么问题,以及如何在输入 3 个不同的值时找到最大值.

I want to know what's wrong with this code and how I can find the max when I input 3 different values.

推荐答案

两件事:将变量 x, y, z 更改为int 并调用该方法为 Math.max(Math.max(x,y),z) 因为它只接受两个参数.

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.

总而言之,更改如下:

    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

这篇关于需要在java中找到最多三个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆