在Java中,從鍵盤輸入三個數(shù)字,求出鍵盤輸入的最值

使用Scanner類,比較大小,先兩兩比較,最后可以得出最值。

1,使用If條件語句來判斷大小的方式:

import java.util.Scanner;

public class ScannerMax {

????????public static void main(String[] args) {

????????????????Scanner sc =new Scanner(System.in);

????????????????System.out.println("請輸入第一個數(shù)字:");

????????????????int a = sc.nextInt();

????????????????System.out.println("請輸入第二個數(shù)字:");

???????????????int b = sc.nextInt();

???????????????System.out.println("請輸入第三個數(shù)字:");

????????????????int c = sc.nextInt();

????????????????if (a>=b && a>=c){

????????????????????System.out.println("最大的數(shù)為:"+a);

????????????????}else if (b>=a && b>=c){

????????????????????System.out.println("最大的數(shù)為:"+b);

????????????????}else {

????????????????????System.out.println("最大的數(shù)為:"+c);

? ? ? ? ? ? ? ? }

? ? ? ? ? }

}

2,使用三目運算符來判斷大小的方式。

import java.util.Scanner;

public class ScannerMax {

????????public static void main(String[] args) {

????????????????Scanner sc =new Scanner(System.in);

????????????????System.out.println("請輸入第一個數(shù)字:");

????????????????int a = sc.nextInt();

????????????????System.out.println("請輸入第二個數(shù)字:");

???????????????int b = sc.nextInt();

???????????????System.out.println("請輸入第三個數(shù)字:");

????????????????int c = sc.nextInt();

? ??????????????int max=a>(b>c?b:c)?a:(b>c?b:c);

? ??????????????System.out.println("最大的數(shù)字是:"+max);

????????}

}

三目運算進(jìn)行的判斷:?int max=a>(b>c?b:c)?a:(b>c?b:c);

可以拆分為兩條語句:int temp=a>b?a:b;

????????????????????????????????????int max=temp>c?temp:c;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容