可能重复:
Find the max of 3 numbers in Java with different data types (Basic Java)
编写一个程序,使用扫描仪读取三个整数(正数)显示最多三个。 (请在不使用任何运算符&&
或||
的情况下完成。这些运算符将很快在课程中介绍。不需要类似的循环。)
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个不同的值时如何找到最大值。
答案 0 :(得分:26)
两件事:将变量x
,y
,z
更改为int
,并将方法调用为Math.max(Math.max(x,y),z)
,因为它只接受两个参数。< / p>
在摘要中,请更改以下内容:
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);
答案 1 :(得分:2)
如果您提供了所看到的错误,这将有所帮助。查看http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html,您将看到max仅返回两个数字之间的最大值,因此您的代码可能甚至无法编译。
首先解决所有编译错误。
然后你的作业将包括通过比较前两个数字并将最大结果与第三个值进行比较来找到最多三个数字。你应该有足够的钱来找到你的答案。
答案 2 :(得分:2)
您应该了解有关java.lang.Math.max
的更多信息:
java.lang.Math.max(arg1,arg2)
只接受2个参数,但你是
在你的代码中写3个参数。double
,int
,long
和float
但你的是
在Math.max函数中编写String
个参数。您需要以所需类型解析它们。由于上述不匹配,您的代码会产生编译时错误。
尝试使用以下更新代码,以解决您的目的:
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: ");
int x = Integer.parseInt(keyboard.nextLine());
int y = Integer.parseInt(keyboard.nextLine());
int z = Integer.parseInt(keyboard.nextLine());
int max = Math.max(x,y);
if(max>y){ //suppose x is max then compare x with z to find max number
max = Math.max(x,z);
}
else{ //if y is max then compare y with z to find max number
max = Math.max(y,z);
}
System.out.println("The max of three is: " + max);
}
}