0
2

一週間で身につくJava言語の基本の解答集 ~応用編の問題~

Posted at

上記の内容のつづき~
応用編の練習問題 解答集

応用問題:(1)静的メンバ

prob1-1.(難易度:★)

package problemex1;

public class Problemex1_1 {

    public static void main(String[] args) {
        int a = (int)(Math.random() * 10) + 1; // 1~10の乱数を発生
        int b = (int)(Math.random() * 10) + 1; // 1~10の乱数を発生
        int resultAdd = add(a, b); // 二つの数の和を求める
        int resultSub = sub(a, b); // 二つの数の差を求める
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println(a + " + " + b + " = " + resultAdd);
        System.out.println(a + " - " + b + " = " + resultSub);
    }

    // 足し算
    static int add(int a, int b) {
        return a + b;
    }

    // 引き算
    static int sub(int a, int b) {
        return a - b;
    }

}

prob1-2.(難易度:★)

package problemex1;
import java.util.Scanner;

public class Problemex1_2 {

    public static void main(String[] args) {
        int a = (int)(Math.random() * 10) + 1; // 1~10の乱数を発生
        int b = (int)(Math.random() * 10) + 1; // 1~10の乱数を発生
        Scanner scanner = new Scanner(System.in);
        System.out.print("c=");
        int c = scanner.nextInt(); // キーボードから整数を入力
        int result = mul(a, b, c); // 三つの数の積を求める
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
        System.out.println(a + " * " + b + " * " + c + " = " + result);
    }

    // 三つの数の積を求める
    static int mul(int a, int b, int c) {
        return a * b * c;
    }

}

prob1-3.(難易度:★)

package problemex1;

public class Problemex1_3 {

    public static void main(String[] args) {
        int vertical = (int)(Math.random() * 10) + 1; // 1~10の乱数を発生
        int horizontal = (int)(Math.random() * 10) + 1; // 1~10の乱数を発生
        System.out.println("たて:" + vertical);
        System.out.println("よこ:" + horizontal);
        square(vertical, horizontal);
    }

    // 縦、横に指定された数の■マークを表示する
    static void square(int vertical, int horizontal) {
        if (vertical <= 0 || horizontal <= 0) {
            return; // 何も表示しない
        }
        for (int i = 0; i < vertical; i++) {
            for (int j = 0; j < horizontal; j++) {
                System.out.print("■");
            }
            System.out.println(); // 改行
        }
    }

}

prob1-4.(難易度:★★)

package problemex1;

public class Counter {
    // カウント
    private int count = 0;
    // トータルのカウント回数
    private static int totalCount = 0;

    // コンストラクタ
    public void reset() {
        count = 0;
    }

    // カウント
    public void count() {
        count++;
        totalCount++;
    }

    // 値の取得
    public int getCount() {
        return count;
    }

    // トータルのカウント回数を取得する静的メソッド
    public static int getTotalCount() {
        return totalCount;
    }

}

Problemex1_4 クラスも以下のように変更。

package problemex1;

public class Problemex1_4 {

    public static void main(String[] args) {
        Counter c1, c2;
        c1 = new Counter();
        c2 = new Counter();
        c1.count();
        c2.count();
        c2.count();
        c2.reset();
        c1.count();
        c1.count();
        c2.count();
        System.out.println("c1のカウント数:" + c1.getCount());
        System.out.println("c2のカウント数:" + c2.getCount());
        System.out.println("トータルのカウント数:" + Counter.getTotalCount()); // 静的メソッドを呼び出す
    }

}

応用問題:(2)継承

prob2-1.(難易度:★)

package problemex2;

class Fighter extends Airplane {
    public void fight() {
        System.out.println("戦闘する");
    }
}

public class Problemex2_1 {
    public static void main(String[] args) {
        Fighter f = new Fighter(); // 戦闘機クラス
        Airplane a = new Airplane(); // 飛行機クラス
        // 飛行機が飛行する
        a.fly();
        // 戦闘機が飛行する
        f.fly();
        // 戦闘機が戦闘する
        f.fight();
    }
}

prob2-2.(難易度:★)

package problemex2;

class NewCalc extends FundCalc {
    // 二つの数の積を出力
    public double mul() {
        return getNumber1() * getNumber2();
    }

    // 二つの数の商を出力
    public double div() {
        if (getNumber2() != 0) {
            return getNumber1() / getNumber2();
        } else {
            System.out.println("0で割ることはできません。");
            return Double.NaN; // 0で割る場合はNaNを返す
        }
    }
}

public class Problemex2_2 {
    public static void main(String[] args) {
        NewCalc n = new NewCalc();
        n.setNumber1(10); // 一つ目の数を設定
        n.setNumber2(2); // 二つ目の数を設定
        System.out.println(n.getNumber1() + " + " + n.getNumber2() + " = " + n.add());
        System.out.println(n.getNumber1() + " - " + n.getNumber2() + " = " + n.sub());
        System.out.println(n.getNumber1() + " * " + n.getNumber2() + " = " + n.mul());
        System.out.println(n.getNumber1() + " / " + n.getNumber2() + " = " + n.div());
    }
}

応用問題:(3)抽象クラス

probex3-1.(難易度:★)

package problemex3;

// 飛行機クラス
public abstract class Airplane {
    // 飛行機のタイプ
    private String type;

    // コンストラクタ
    public Airplane(String type) {
        this.type = type;
    }

    // タイプの取得
    public String getType() {
        return type;
    }

    // 飛行する
    public abstract void fly();
}

// 戦闘機クラス
class FighterAircraft extends Airplane {
    // コンストラクタ
    public FighterAircraft() {
        super("戦闘機");
    }

    // 飛行する
    public void fly() {
        System.out.println("攻撃に出るために飛行します。");
    }

    // 戦闘する
    public void fight() {
        System.out.println("戦闘します。");
    }
}

// 旅客機クラス
class PassengerPlane extends Airplane {
    // コンストラクタ
    public PassengerPlane() {
        super("旅客機");
    }

    // 飛行する
    public void fly() {
        System.out.println("乗客を乗せて目的地まで飛行します。");
    }

    // 乗客を運ぶ
    public void carryPassengers() {
        System.out.println("乗客を目的地まで運びます。");
    }
}

public class Problemex3_1 {
    public static void main(String[] args) {
        FighterAircraft fighter = new FighterAircraft();
        PassengerPlane airliner = new PassengerPlane();
        
        fighter.fly();
        fighter.fight();
        
        airliner.fly();
        airliner.carryPassengers();
    }
}

prob3-2.(難易度:★★)

package problemex3;

// コンピュータの抽象クラス
public abstract class Computer {
    // コンピュータのタイプ
    private String type;

    // コンストラクタ
    public Computer(String type) {
        this.type = type;
    }

    // 入力処理
    public abstract void input();

    // 出力処理
    public abstract void output();

    // 通信処理
    public void communication() {
        System.out.println("インターネットで通信");
    }

    // タイプの出力
    public void showType() {
        System.out.println("コンピュータの種類:" + type);
    }
}

// パーソナルコンピュータクラス
class PersonalComputer extends Computer {
    // コンストラクタ
    public PersonalComputer() {
        super("パーソナルコンピュータ");
    }

    // 入力処理
    public void input() {
        System.out.println("キーボード・マウスで入力");
    }

    // 出力処理
    public void output() {
        System.out.println("ディスプレイに出力");
    }
}

// タブレットPCクラス
class TabletPC extends Computer {
    // コンストラクタ
    public TabletPC() {
        super("タブレットPC");
    }

    // 入力処理
    public void input() {
        System.out.println("タッチパネルディスプレイをタップして操作");
    }

    // 出力処理
    public void output() {
        System.out.println("タッチパネルディスプレイに出力");
    }
}

// スマートフォンクラス
class SmartPhone extends Computer {
    // コンストラクタ
    public SmartPhone() {
        super("スマートフォン");
    }

    // 入力処理
    public void input() {
        System.out.println("タッチパネルディスプレイをタップして操作");
    }

    // 出力処理
    public void output() {
        System.out.println("タッチパネルディスプレイに出力");
    }

    // 通信処理(スマートフォン用にオーバーライド)
    public void communication() {
        System.out.println("インターネットと電話回線で通信");
    }
}

public class Problemex3_2 {
    public static void main(String[] args) {
        Computer[] computers = new Computer[3];
        computers[0] = new PersonalComputer(); // パーソナルコンピュータ
        computers[1] = new TabletPC(); // タブレットPC
        computers[2] = new SmartPhone(); // スマートフォン

        for (Computer computer : computers) {
            computer.showType();
            computer.input();
            computer.output();
            computer.communication();
            System.out.println("--------------------------------------");
        }
    }
}

応用問題:(4)インターフェース

prob4-1.(難易度:★)

package problemex4;

// 電話インターフェース
interface IPhone {
    void callPhone();
    void recievePhone();
}

// メーラーインターフェース
interface IMailer {
    void sendMail();
    void recieveMail();
}

// コンピュータインターフェース
interface IComputer {
    void playGame();
    void borwseWeb();
}

// 携帯電話クラス
public class CellPhone implements IPhone, IMailer, IComputer {
    public void sendMail() {
        System.out.println("メールを送る");
    }

    public void recieveMail() {
        System.out.println("メールを受信する");
    }

    public void borwseWeb() {
        System.out.println("ウェブを閲覧する");
    }

    public void playGame() {
        System.out.println("ゲームをする");
    }

    public void callPhone() {
        System.out.println("電話を掛ける");
    }

    public void recievePhone() {
        System.out.println("電話を受ける");
    }
}

public class Problemex4_1 {
    public static void main(String[] args) {
        CellPhone cp = new CellPhone();
        funcPhone(cp);
        funcMailer(cp);
        funcComputer(cp);
    }

    // 電話としての処理
    public static void funcPhone(IPhone phone) {
        phone.callPhone();      // 電話を掛ける
        phone.recievePhone();   // 電話を受ける
    }

    // メーラーとしての処理
    public static void funcMailer(IMailer mailer) {
        mailer.sendMail();      // メールを送信する
        mailer.recieveMail();   // メールを受信する
    }

    // コンピュータとしての処理
    public static void funcComputer(IComputer computer) {
        computer.playGame();    // ゲームをする
        computer.borwseWeb();   // ウェブを閲覧する
    }
}

prob4-2.(難易度:★)

package problemex4;

// アラームインターフェース
interface IAlarm {
    void alarm();
    void setAlarm();
    void stopAlarm();
}

// 時計インターフェース
interface IClock {
    void showTime();
    void adjustTime();
}

// アラームつき時計クラス
public class AlarmClock implements IClock, IAlarm {
    public void alarm() {
        System.out.println("アラームを鳴らす");
    }

    public void setAlarm() {
        System.out.println("アラームをセットする");
    }

    public void stopAlarm() {
        System.out.println("アラームを止める");
    }

    public void showTime() {
        System.out.println("時刻を知る");
    }

    public void adjustTime() {
        System.out.println("時刻を修正する");
    }
}

public class Problemex4_2 {
    public static void main(String[] args) {
        AlarmClock ac = new AlarmClock(); // アラーム付き時計クラスのインスタンスを生成
        funcAlarm(ac);
        funcClock(ac);
    }

    // アラームとしての処理
    public static void funcAlarm(IAlarm alarm) {
        alarm.setAlarm();   // アラームのセット
        alarm.alarm();      // アラームを鳴らす
        alarm.stopAlarm();  // アラームを止める
    }

    // 時計としての処理
    public static void funcClock(IClock clock) {
        clock.adjustTime(); // 時間を調整する
        clock.showTime();   // 時間を表示する
    }
}

応用問題:コレクション①

probex5-1.(難易度:★)

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class Problemex5_1 {
    public static void main(String[] args) {
        List<Integer> evenNumbers = new ArrayList<>();
        List<Integer> oddNumbers = new ArrayList<>();
        Random rand = new Random();

        while (true) {
            int num = rand.nextInt(11);
            System.out.print("0~10の値を出力:" + num + "\n");

            if (num == 0) {
                break;
            }

            if (num % 2 == 0) {
                evenNumbers.add(num);
            } else {
                oddNumbers.add(num);
            }
        }

        System.out.print("偶数 : ");
        for (Integer even : evenNumbers) {
            System.out.print(even + " ");
        }

        System.out.print("\n奇数 : ");
        for (Integer odd : oddNumbers) {
            System.out.print(odd + " ");
        }
    }
}

probex5-2.(難易度:★)

import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.Collections;

public class Problemex5_2 {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        Random rand = new Random();

        while (true) {
            int num = rand.nextInt(11);
            System.out.print("0~10の値を出力:" + num + "\n");

            if (num == 0) {
                break;
            }

            numbers.add(num);
        }

        Collections.reverse(numbers);

        for (Integer number : numbers) {
            System.out.print(number + " ");
        }
    }
}

probex5-3.(難易度:★★)

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class Problemex5_3 {
    public static void main(String[] args) {
        List<List<Integer>> groups = new ArrayList<>(10);
        Random rand = new Random();

        for (int i = 0; i < 10; i++) {
            groups.add(new ArrayList<>());
        }

        while (true) {
            int num = rand.nextInt(101);
            System.out.print("0~100の値を出力:" + num + "\n");

            if (num == 0) {
                break;
            }

            int lastDigit = num % 10;
            groups.get(lastDigit).add(num);
        }

        for (int i = 0; i < groups.size(); i++) {
            if (!groups.get(i).isEmpty()) {
                System.out.print("一の位が" + i + " : ");
                for (Integer num : groups.get(i)) {
                    System.out.print(num + " ");
                }
                System.out.println();
            }
        }
    }
}

probex5-4.(難易度:★★)

import java.io.*;
import java.util.List;
import java.util.ArrayList;

public class Problemex5_4 {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        List<String> inputList = new ArrayList<>();

        while (true) {
            System.out.print("文字列を入力:");
            String input = br.readLine();

            if (input.isEmpty()) {
                break;
            }

            inputList.add(input);
        }

        for (String input : inputList) {
            System.out.print(input + " ");
        }
    }
}

probex5-5.(難易度:★★)

import java.io.*;
import java.util.List;
import java.util.ArrayList;

public class Problemex5_5 {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        List<String> inputList = new ArrayList<>();

        while (true) {
            System.out.print("文字列を入力:");
            String input = br.readLine();

            if (input.isEmpty()) {
                break;
            }

            inputList.add(input);
        }

        System.out.print("5文字未満の単語:");
        for (String input : inputList) {
            if (input.length() < 5) {
                System.out.print(input + " ");
            }
        }
    }
}

probex5-6.(難易度:★)

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class Problemex5_6 {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        Random rand = new Random();

        while (true) {
            int num = rand.nextInt(11);
            System.out.print("0~10の値を出力:" + num + "\n");

            if (num == 0) {
                break;
            }

            numbers.add(num);
        }

        numbers.remove(Integer.valueOf(2));

        for (Integer number : numbers) {
            System.out.print(number + " ");
        }
    }
}

probex5-7.(難易度:★★)

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class Problemex5_7 {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        Random rand = new Random();

        while (true) {
            int num = rand.nextInt(11);
            System.out.print("0~10の値を出力:" + num + "\n");

            if (num == 0) {
                break;
            }

            int index = 0;
            for (Integer number : numbers) {
                if (num < number) {
                    break;
                }
                index++;
            }
            numbers.add(index, num);
        }

        System.out.print("出力された数:");
        for (Integer number : numbers) {
            System.out.print(number + " ");
        }
    }
}

応用問題:(6)コレクション②

probex6-1.(難易度:★)

import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;

public class Problemex6_1 {

    public static void main(String[] args) {
        // 英単語と日本語の対応表を作成
        Map<String, String> dictionary = new HashMap<>();
        dictionary.put("cat", "猫");
        dictionary.put("dog", "犬");
        dictionary.put("bird", "鳥");
        dictionary.put("tiger", "トラ");

        Scanner scanner = new Scanner(System.in);
        System.out.print("英語で動物の名前を入力してください:");
        String input = scanner.nextLine();

        if (dictionary.containsKey(input)) {
            String japaneseTranslation = dictionary.get(input);
            System.out.println("「" + japaneseTranslation + "」です。");
        } else {
            System.out.println("対応するデータは登録されていません。");
        }
    }
}

probex6-2.(難易度:★★)

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Problemex6_2 {

    public static void main(String[] args) {
        // 漢数字の対応表を作成
        Map<Character, String> kanjiMap = new HashMap<>();
        kanjiMap.put('0', "〇");
        kanjiMap.put('1', "一");
        kanjiMap.put('2', "二");
        kanjiMap.put('3', "三");
        kanjiMap.put('4', "四");
        kanjiMap.put('5', "五");
        kanjiMap.put('6', "六");
        kanjiMap.put('7', "七");
        kanjiMap.put('8', "八");
        kanjiMap.put('9', "九");

        Scanner scanner = new Scanner(System.in);
        System.out.print("整数の値を入力してください:");
        String input = scanner.nextLine();

        if (isNumeric(input)) {
            StringBuilder result = new StringBuilder();
            int length = input.length();
            int leadingZeros = length % 3;

            if (leadingZeros != 0) {
                result.append(kanjiMap.get(input.charAt(0)));
                if (leadingZeros > 1 || length == 1) {
                    result.append("百");
                }
            }

            for (int i = leadingZeros; i < length; i++) {
                char digit = input.charAt(i);
                if (digit != '0') {
                    if (result.length() > 0) {
                        result.append(",");
                    }
                    result.append(kanjiMap.get(digit));
                    int position = length - i - 1;
                    switch (position % 4) {
                        case 1:
                            result.append("十");
                            break;
                        case 2:
                            result.append("百");
                            break;
                        case 3:
                            result.append("千");
                            break;
                    }
                }
            }

            System.out.println("変換結果:" + result.toString());
        } else {
            System.out.println("整数の値を入力してください。");
        }
    }

    public static boolean isNumeric(String str) {
        return str.matches("\\d+");
    }
}

probex6-3.(難易度:★)

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class Problemex6_3 {

    public static void main(String[] args) {
        Random random = new Random();
        Set<Integer> numbers = new HashSet<>();

        System.out.print("乱数:");
        for (int i = 0; i < 10; i++) {
            int randomNumber = random.nextInt(10) + 1; // 1から10までの乱数
            numbers.add(randomNumber);
            System.out.print(" " + randomNumber);
        }

        List<Integer> sortedNumbers = new ArrayList<>(numbers);
        Collections.sort(sortedNumbers); // 数字を昇順でソート

        System.out.println();
        System.out.print("出現した数:");
        for (int number : sortedNumbers) {
            System.out.print(" " + number);
        }
    }
}

probex6-4.(難易度:★★)

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.Collections;

public class Problemex6_4 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("英単語を入力:");
        String inputWord = scanner.nextLine().toLowerCase(); // 英単語を小文字に変換
        scanner.close();
        
        Set<Character> uniqueCharacters = new HashSet<>();
        
        for (int i = 0; i < inputWord.length(); i++) {
            char character = inputWord.charAt(i);
            if (Character.isLetter(character)) {
                uniqueCharacters.add(character);
            }
        }
        
        List<Character> sortedCharacters = new ArrayList<>(uniqueCharacters);
        Collections.sort(sortedCharacters); // ソート
        
        System.out.print("使用されているアルファベット:");
        for (char character : sortedCharacters) {
            System.out.print(" " + character);
        }
    }
}

probex6-5.(難易度:★)

package problemex6;

public class Problemex6_5 {

    public static void main(String[] args) {
        String s1 = "hoge";
        String s2 = new String("hoge");
        
        if (s1.equals(s2)) {
            System.out.println(s1 + "と" + s2 + "は、同じ文字列です。");
        } else {
            System.out.println(s1 + "と" + s2 + "は、同じ文字列ではありません。");
        }
    }
}

応用問題:(7)例外処理

prob7-1.(難易度:★)

package problemex7;

public class Problemex7_1 {

    public static void main(String[] args) {
        int a[] = { 0, 1, 2 };
        // 配列の内容を表示
        for (int i = 0; i < 4; i++) {
            try {
                System.out.println("a[" + i + "]=" + a[i]);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("配列の範囲を超えています。");
            }
        }
    }
}

prob7-2.(難易度:★)

package problemex7;

public class Problemex7_2 {

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                try {
                    if (j == 0) {
                        throw new ArithmeticException("0で割り算はできません。");
                    }
                    System.out.print(i + "/ " + j + " = " + i / j + " ");
                } catch (ArithmeticException e) {
                    System.out.print(e.getMessage() + " ");
                }
            }
            System.out.println();
        }
    }
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2