落書きノート

ふと自分が気になった事を書いてます

Javaで問題を解く

解きながら学ぶJava 入門編

解きながら学ぶJava 入門編

// q7_10

import java.util.Scanner;
import java.util.Random;

class q7_10 {
    public static void main(String[] args) {
        System.out.println("暗算力トレーニング!!");
        int x,y,z;
        int op;
        int sum = 0;
        int answer;
        int retry;
        do {
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
            x = rand.nextInt(900) + 100;
            y = rand.nextInt(900) + 100;
            z = rand.nextInt(900) + 100;
            op = rand.nextInt(4);
            while(true) {
                switch(op) {
                case 0:
                    sum = x + y + z;
                    System.out.print(x + " + " + y + " + " + z + " = ");
                    break;
                case 1:
                    sum = x + y - z;
                    System.out.print(x + " + " + y + " - " + z + " = ");
                    break;
                case 2:
                    sum = x - y + z;
                    System.out.print(x + " - " + y + " + " + z + " = ");
                    break;
                case 3:
                    sum = x - y - z;
                    System.out.print(x + " - " + y + " - " + z + " = ");
                    break;
                }
                answer = scan.nextInt();
                if(sum == answer)
                    break;
                else
                    System.out.println("違いますよ!!");
            }
            System.out.print("もう一度?<Yes...1/No...0> : ");
            retry = scan.nextInt();
        } while(retry == 1);
    }
}

// q7_11

import java.util.Scanner;

class q7_11 {
    static int pow(int n) {
        int pow = 2;
        for(int i = 1; i < n; i++) {
            pow *= 2;
        }
        return pow;
    }
    public static void main(String[] args) {
        int x, n;
        Scanner scan = new Scanner(System.in);
        System.out.println("整数xをnビットシフトします。");
        System.out.print("x : ");
        x = scan.nextInt();
        System.out.print("n : ");
        n = scan.nextInt();
        int answer1 = x * pow(n);
        int answer2 = x / pow(n);
        int answer3 = x << n;
        int answer4 = x >> n;
        System.out.printf("[a] x × (2の%d乗) = %d\n", n, answer1);
        System.out.printf("[b] x ÷ (2の%d乗) = %d\n", n, answer2);
        System.out.printf("[c] x << %d = %d\n", n, answer3);
        System.out.printf("[d] x >> %d = %d\n", n, answer4);
        System.out.println("[a]と[c]の値は一致" + (answer1 == answer3 ? "します。" : "しません。"));
        System.out.println("[b]と[d]の値は一致" + (answer2 == answer4 ? "します。" : "しません。"));
    }
}