[英]Find the maximum of three integers
我編寫了一個程序來查找給定三個數字中的最大值。 它適用於單個數字,但不適用於三位數字。 為什么不?
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));
只有當 a 大於 b 時,您的程序才能工作。 如果您想使用簡單的 if else 下面的代碼將起作用。
if(a>b && a>c )
System.out.println("maximum of the given numbers "+a);
else if (b>a && b>c)
System.out.println("maximum of the given numbers "+b);
else
System.out.println("maximum of the given numbers "+c);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.