可能的重复:
在 Java 中查找不同数据类型的 3 个数字中的最大值(基本 Java) https://stackoverflow.com/questions/4982210/find-the-max-of-3-numbers-in-java-with-different-data-types-basic-java
编写一个程序,使用扫描仪读取三个整数(正数),显示三中最大的数。 (请在不使用任何运算符的情况下完成&&
or ||
。这些运算符将很快在课堂上介绍。同样,不需要循环。)
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 个不同的值时如何找到最大值。
两件事:改变变量x
, y
, z
as int
并将该方法调用为Math.max(Math.max(x,y),z)
因为它只接受两个参数。
总而言之,更改如下:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)