java - 求三个整数的最大值
问题描述
我编写了一个程序来查找给定三个数字中的最大值。它适用于单个数字,但不适用于三位数字。为什么不?
package practice;
import java.util.Scanner;
public class AllPractice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if(a > b) {
if (a > c) {
System.out.println("maximum of the given numbers "+a);
}else {
if (b > a) {
if (b > c) {
System.out.println("maximum of the given numbers "+b);
}
}else {
System.out.println("maximum of the given numbers "+c);
}
}
}
}
}
解决方案
您的代码不起作用,因为如果您的变量a
小于b
,则您永远不会输入第一个条件。
一个简单的单线解决方案/替代方案:
int max = Collections.max(Arrays.asList(a, b, c));
推荐阅读
- python - Python/Discord——我正在制作一个不和谐的机器人,但 os 模块存在一些问题:
- python - 将 Python 函数应用于一个 pandas 列并将输出应用于多个列
- javascript - 如何一次在数组中设置给定属性的所有值
- javascript - NodeJS - 返回未定义的问题
- python - 如何打印文件中的所有电话号码
- python - 有条件地向熊猫数据框添加一列
- ctags - 如何为自定义文件格式定义 ctag 解析器
- typescript - 显示模块 - 谁的目标缺少构造签名?
- python - Beautifulsoup 匹配空类
- node.js - 使用nodeJS在Sequelize中创建行后如何重新加载表?