【Java】演習問題3−13【新・明解Java入門】

演習3-13

キーボードから読み込んだ三つの整数値の中央値を求めて表示するプログラムを作成
※2,3,1の中央値は2/1,2,1の中央値は1/3,3,3の中央値は3

(この問題は、解答が正確かどうか分かりません。。。)

 解答

public class q3_13 {
    public static void main(String[] args){
        System.out.println("三つの整数を入力してください");
        int x = new java.util.Scanner(System.in).nextInt();
        int y = new java.util.Scanner(System.in).nextInt();
        int z = new java.util.Scanner(System.in).nextInt();
        int max = x;
        int min = y;
        if(max < y){
            max = y;
        }
        if(max < z){
            max = z;
        }
        if(min > x){
            min = x;
        }
        if(min > z){
            min = z;
        }
        if(max == x && min == y){
            System.out.println("中央値は" + z);
        }else if(max == x && min == z){
            System.out.println("中央値は" + y);
        }else if(max == y && min == z){
            System.out.println("中央値は" + x);
        }else if(max == y && min == x){
            System.out.println("中央値は" + z);
        }else if(max == z && min == x){
            System.out.println("中央値は" + y);
        }else if(max == z && min == y){
            System.out.println("中央値は" + x);
        }   
    }
}