本题目要求读入2个整数A和B,然后输出两个数的最大值。
输入格式:
输入在一行中给出2个绝对值不超过1000的整数A和B。
输出格式:
对每一组输入,在一行中输出最大值。
输入样例:
在这里给出一组输入。例如:
18 -299
输出样例:
在这里给出相应的输出。例如:
18
代码如下:
import java.util.Scanner;
public class Main{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
int a=sc.nextInt();
int b=sc.nextInt();
int maxInt=Integer.max(a,b);
System.out.println(maxInt);
}
sc.close();
}
}
学习记录:
这里总结几种最值判断的方法。
1、基本类型 / 数组:通过循环遍历 + 条件判断;
2、仅仅只是两个值的大小比较;
Java 的包装类(如Integer、Double等)提供了静态方法 max(x, y),可直接返回两个同类型值的最大值:
// Integer的max方法
int maxInt = Integer.max(100, 200); // 200
// Double的max方法
double maxDouble = Double.max(3.14, 2.71); // 3.14
// Long的max方法
long maxLong = Long.max(100000L, 99999L); // 100000L
3、集合中的最大值;
对于List等集合,可以使用 java.util.Collections 工具类的 max() 方法:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(2);
list.add(8);
int max = Collections.max(list); // 获取集合最大值
System.out.println("集合最大值:" + max); // 输出8
}
}
以上就是今天的做题分享。