LoginSignup
0
0

Java勉強会(解答サンプル)

Last updated at Posted at 2024-04-14

java勉強会(4/13開催)でのサンプル解答です

解答は何種類もありその中の一つというだけなので、こういう書き方もあるんだなあ、程度にお考えください。

おそらく月曜日にコンストラクタなどを学ぶのでそれまでの命・・・

Question01

public class Question01 {
    public static void main(String[] args) {
        // 問題1
        // 整数値を2つ受け取り、それらの和、差、積、商を出力するメソッドを作成してください。
        // 入力値のチェックは不要です。
        // 作成したメソッドを以下で呼び出してください。
        int a = 10;
        int b = 3;
        calculate(a, b);
    }

    // calculateメソッドを実装してください

    public static void calculate(int x, int y) {
        // 和
        System.out.printf("和: %d + %d = %d%n", x, y, x + y);
        // 差
        System.out.printf("差: %d - %d = %d%n", x, y, x - y);
        // 積
        System.out.printf("積: %d * %d = %d%n", x, y, x * y);
        // 商 (整数の除算)
        System.out.printf("商: %d / %d = %d%n", x, y, x / y);
    }
}

Question02

public class Question02 {
    public static void main(String[] args) {
        // 問題2
        // 整数値を1つ受け取り、その値が奇数か偶数かを出力するメソッドを作成してください。
        // 作成したメソッドを以下で呼び出してください。
        int num = 7;
        boolean isEven = checkEven(num);
        System.out.println(isEven); // false
    }

    // checkEven メソッドを実装してください
    public static boolean checkEven(int num) {
        return num % 2 == 0;
    }
}

Question03

public class Question03 {
    public static void main(String[] args) {
        int a0 = 5, b0 = 2;
        sortNumbers(a0, b0); // 2, 5 が期待されます

        int a1 = 1, b1 = 4;
        sortNumbers(a1, b1); // 1, 4 が期待されます
    }

    // sortNumbers メソッドの実装
    public static void sortNumbers(int x, int y) {
        if (x > y) {
            // x と y を交換する
            int temp = x;
            x = y;
            y = temp;
        }
        System.out.printf("%d, %d%n", x, y);
    }
}

Question04

public class Question04 {
    public static void main(String[] args) {
        // 問題4
        // 正の整数値を1つ受け取り、その数値の階乗を計算するメソッドを作成してください。
        // 作成したメソッドを以下で呼び出してください。
        int num = 5;
        long factorial = calculateFactorial(num);
        System.out.println(factorial); // 120
    }

    // calculateFactorial メソッドの実装
    public static int calculateFactorial(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("正の整数を入力してください");
        }
        
        int factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        
        return factorial;
    }
}

Question05

public class Question05 {
    public static void main(String[] args) {
        // 問題5
        // 整数値を受け取り、その値が正の数かどうかを判定するメソッドを作成してください。
        // 作成したメソッドを以下で呼び出してください。
        int num = -3;
        boolean isPositive = checkPositive(num);
        System.out.println(isPositive); // false
    }
    
    // checkPositive メソッドを実装してください
    public static boolean checkPositive(int num) {
        return num >= 0;
    }
}

Question06

public class Question06 {
    public static void main(String[] args) {
        // 問題6
        // 1からnまでの整数の和を計算するメソッドを作成してください。
        // nの値は以下で指定してあります。
        // 作成したメソッドを呼び出して結果を出力してください。
        int n = 10;
        int sum = calculateSum(n);
        System.out.println(sum); // 55
    }
    
    // calculateSum メソッドを実装してください。
    // for文かwhile文を使用すること。
    public static int calculateSum(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
}

Question07

public class Question07 {
    public static void main(String[] args) {
        // 問題7
        // 整数値の配列を1つ受け取り、その配列内で最大値と最小値を見つけるメソッドを作成してください。
        // 作成したメソッドを以下で呼び出してください。
        int[] numbers = {5, 2, 8, 1, 9};
        findMinMax(numbers);
        // 期待する出力:
        // 最大値: 9
        // 最小値: 1
    }

    // findMinMax メソッドを実装してください。
    // for文かwhile文を使用すること。
    public static void findMinMax(int[] numbers) {
        int min = numbers[0];
        int max = numbers[0];
        for (int num : numbers) {
            if (num < min) {
                min = num;
            }
            if (num > max) {
                max = num;
            }
        }
        System.out.printf("min: %d, max: %d", min, max);
    }
}

Question08

public class Question08 {
    public static void main(String[] args) {
        // 問題8
        // 正の整数値を受け取り、その数値が偶数かどうかを判定するメソッドを作成してください。
        // さらに、その数値までの偶数をすべて出力するメソッドも作成してください。
        // 作成したメソッドを以下で呼び出してください。
        int num = 10;
        boolean isEven = checkEven(num);
        System.out.println(isEven); // true
        printEvenNumbers(num);
        // 期待する出力: 2, 4, 6, 8, 10
    }
    
    // checkEven メソッドを実装してください。
    public static boolean checkEven(int num) {
        return num % 2 == 0;
    }
    // printEvenNumbers メソッドを実装してください。
    public static void printEvenNumbers(int num) {
        for (int i = 1; i <= num; i++) {
            if (checkEven(i)) {
                System.out.printf("%d ", i);
            }
        }
    }
    // これらのメソッドでfor文かwhile文、if文を使用すること。
    
}

Question09

public class Question09 {
    public static void main(String[] args) {
        // 問題9
        // 配列を出力するメソッドを作成してください。
        // 作成したメソッドを以下で呼び出してください。
        int[] numbers = {1, 2, 3, 4, 5};


        printArray(numbers);
        // 期待する出力: 1, 2, 3, 4, 5
    }


    // printArray メソッドを実装してください。
    public static void printArray(int[] numbers) {
        for (int i = 0; i < numbers.length-1; i++) {
            System.out.printf("%d, ", numbers[i]);
        }
        System.out.printf("%d", numbers[numbers.length-1]);
    }

    // これらのメソッドでfor文とif文を使用すること。
}

Question10

public class Question10 {
    public static void main(String[] args) {
        // 問題10
        // 整数値を受け取り、それらの値の大小を比較するメソッドを作成してください。
        // メソッドのオーバーロードを利用して、整数2つ・3つを受け取るバージョンを両方作成してください。
        // 作成したメソッドを以下で呼び出してください。
        int a = 5, b = 10;
        int larger = max(a, b);
        System.out.println(larger); // 10

        int x = 7, y = 3, z = 9;
        int maximum = max(x, y, z);
        System.out.println(maximum); // 9
    }

    // max メソッドを作成してください。(整数2つのオーバーロード)
    public static int max(int a, int b) {
        return a > b ? a : b;
    }
    // max メソッドを作成してください。(整数3つのオーバーロード)
    public static int max(int a, int b, int c) {
        int max = a;
        if (b > max) {
            max = b;
        }
        if (c > max) {
            max = c;
        }
        return max;
    }
    // これらのメソッドでif文を使用すること。
}

Question11

Employee.java
public class Employee {
    String name;
    int age;
    String department;
    
    public void printInfo() {
        System.out.printf("Name: %s\nAge: %d\nDepartment: %s\n", name, age, department);
    }
}

Question12

Order.java
public class Order {
    int orderNumber;
    String itemName;
    int quantity;

    public void printOrder() {
        System.out.printf("注文番号: %d, 商品名: %s, 数量: %d\n", orderNumber, itemName, quantity);
    }
}

Question13

Question13.java
public class Question13 {
    public static void main(String[] args) {
        // 問題13
        // 従業員の情報を表すクラス Employee を作成してください。
        // 従業員には名前(name)、年齢(age)、部署(department)、給与(salary)の情報があります。
        // Employeeクラスには以下のフィールドを定義してください。
        //   name (String型)
        //   age (int型)
        //   department (String型)
        //   salary (int型)
        // また、従業員の給与を計算するメソッド calculateSalary() を作成してください。
        // 給与計算のロジックは以下の通りです。
        // ・20歳未満の場合、基本給与は15万円
        // ・20歳以上30歳未満の場合、基本給与は20万円
        // ・30歳以上の場合、基本給与は25万円

        // 以下のEmployeeインスタンスの配列を用意してください。
        // Employee("山田太郎", 25, "営業部")
        // Employee("佐藤花子", 32, "総務部")
        // Employee("木村健一", 19, "企画部")
        // Employee("高橋美咲", 28, "営業部")

        Employee taro = new Employee();
        taro.name = "山田太郎";
        taro.age = 25;
        taro.department = "営業部";

        Employee hanako = new Employee();
        hanako.name = "佐藤花子";
        hanako.age = 32;
        hanako.department = "総務部";

        Employee kenichi = new Employee();
        kenichi.name = "木村健一";
        kenichi.age = 19;
        kenichi.department = "企画部";

        Employee misaki = new Employee();
        misaki.name = "高橋美咲";
        misaki.age = 28;
        misaki.department = "営業部";

        Employee[] employees = {
            taro, hanako, kenichi, misaki
        };

        // for文 または enhanced for文を使用して、
        // 配列内の各Employeeインスタンスの給与を計算し、calculateSalary()メソッドで設定してください。
        // 設定後、各従業員の情報を出力してください。

        for (Employee employee : employees) {
            employee.calculateSalary();
            System.out.printf("氏名:%s%n 部署:%s%n 年齢:%d%n 給料:%d%n\n", employee.name, employee.department, employee.age,employee.salary);
        }
    }

    // Employee クラスを定義してください
    // calculateSalary() メソッドを実装してください
}
Employee.java
public class Employee {
    String name;
    int age;
    String department;
    int salary;

    public int calculateSalary() {
        if (this.age < 20) {
            this.salary = 150000;
        } else if (this.age < 30) {
            this.salary = 200000;
        } else {
            this.salary = 300000;
        }
        return this.salary;
    }
}

Question14

Question14.java
public class Question14 {
    public static void main(String[] args) {
        // 問題14
        // 学生の成績情報を扱うクラス Student を作成してください。
        // 学生には名前(name)、国語の点数(japaneseScore)、数学の点数(mathScore)、英語の点数(englishScore)の情報があります。
        // Studentクラスには以下のフィールドを定義してください。
        //   name (String型)
        //   japaneseScore (int型)
        //   mathScore (int型)
        //   englishScore (int型)
        // また、合計点数を計算するメソッド calculateTotalScore() と平均点数を計算するメソッド calculateAverageScore() を作成してください。

        // 作成したStudentクラスを使用し、以下の処理を行ってください。
        Student taro = new Student();
        taro.name = "山田太郎";
        taro.japaneseScore = 80;
        taro.mathScore = 75;
        taro.englishScore = 90;
        int totalScoreTaro = taro.calculateTotalScore();
        double averageScoreTaro = taro.calculateAverageScore();
        System.out.println(taro.name + "の合計点: " + totalScoreTaro + "点");
        System.out.println(taro.name + "の平均点: " + averageScoreTaro + "点");

        Student hanako = new Student();
        hanako.name = "佐藤花子";
        hanako.japaneseScore = 92;
        hanako.mathScore = 68;
        hanako.englishScore = 84;
        int totalScoreHanako = hanako.calculateTotalScore();
        double averageScoreHanako = hanako.calculateAverageScore();
        System.out.println(hanako.name + "の合計点: " + totalScoreHanako + "点");
        System.out.println(hanako.name + "の平均点: " + averageScoreHanako + "点");
    }

    // Student クラスを定義してください
    // calculateTotalScore() メソッドと calculateAverageScore() メソッドを実装してください
}
Student.java
public class Student {
    String name;
    int japaneseScore;
    int mathScore;
    int englishScore;

    public int calculateTotalScore() {
        return japaneseScore + mathScore + englishScore;
    }

    public double calculateAverageScore() {
        return (double) calculateTotalScore() / 3;
    }
}

Question15

InventoryManager
public class InventoryManager {
    public String name;
    public int stockCount;
    public int safetyStock;

    public int shipStock(int quantity) {
        if (stockCount - quantity >= safetyStock) {
            stockCount -= quantity;
            return stockCount;
        } else {
            return -1;
        }
    }
}

Question16

BankAccount.java
public class BankAccount {
    public int accountNumber;
    public String accountName;
    public int balance;

    public boolean withdraw(int amount) {
        if (balance >= amount) {
            balance -= amount;
            return true;
        } else {
            return false;
        }
    }

    public boolean deposit(int amount) {
        balance += amount;
        return true;
    }
}

Question17

InventoryManager.java
public class InventoryManager {
    String productName;
    int unitPrice;
    int stockCount;

    public int sellStock(int salesCount){
        if (salesCount <= stockCount){
            stockCount -= salesCount;
            return (stockCount - salesCount)*unitPrice;
        } else {return 0;}
    }
}

Question18

public class Question18 {
    public static void main(String[] args) {
        // 問題2
        // 文字列を1つ受け取り、その文字列が回文かどうかを判定するメソッドを作成してください。
        // 回文とは、前からも後ろからも同じ文字列になるものです。
        // 作成したメソッドを以下で呼び出してください。
        // 他にもこんな回文があったり
        //        madam
        //        civic
        //        refer
        //        level
        //        noon
        String str = "madam";
        boolean isPalindrome = checkPalindrome(str);
        System.out.println(isPalindrome); // true
    }
    
    // checkPalindrome メソッドを実装してください
    public static boolean checkPalindrome(String str) {
        if (str == null || str.length() == 0) {
            return true;
        }
        int start = 0;
        int end = str.length() - 1;
        while (start < end) {
            if (str.charAt(start) != str.charAt(end)) {
                return false;
            }
            start += 1;
            end -= 1;

        }
        return true;
    }
}

Question19

Question19.java
import java.util.Scanner;

public class Question19 {
    public static void main(String[] args) {
        Inventory inventory = new Inventory();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("Enter 'add' to add a product, 'print' to print all products, or 'exit' to quit: ");
            String input = scanner.nextLine();

            switch (input) {
                case "add":
                    System.out.print("Enter product name: ");
                    String name = scanner.nextLine();
                    System.out.print("Enter price: ");
                    int price = scanner.nextInt();
                    System.out.print("Enter stock: ");
                    int stock = scanner.nextInt();
                    scanner.nextLine(); // Consume newline character

                    inventory.addProduct(name, price, stock);
                    break;
                case "print":
                    inventory.printAllProducts();
                    break;
                case "exit":
                    System.out.println("Exiting program...");
                    scanner.close();
                    return;
                default:
                    System.out.println("Invalid input. Please try again.");
            }
        }
    }
}
Inventory.java
import java.util.ArrayList;
import java.util.List;

public class Inventory {
    public List<Product> products;

    public Inventory() {
        this.products = new ArrayList<>();
    }

    public void addProduct(String name, int price, int stock) {
        Product product = new Product();
        product.name = name;
        product.price = price;
        product.stock = stock;
        products.add(product);
    }

    public void printAllProducts() {
        for (Product product : products) {
            product.printInfo();
            System.out.println();
        }
    }
}
Product.java
public class Product {
    String name;
    int price;
    int stock;


    public void printInfo() {
        System.out.printf("Product Name:%s",name);
        System.out.printf("Price:$%s",price);
        System.out.printf("Stock:%s",stock);
    }
}

Question20


public class Question20 {
    public static void main(String[] args) {
        // 問題20
        // 整数値の配列を1つ受け取り、その配列内で重複する要素を削除するメソッドを作成してください。
        // 削除後の配列を出力するメソッドも作成してください。
        // 作成したメソッドを以下で呼び出してください。
        int[] numbers = {1, 2, 3, 2, 4, 1, 5};
        int[] uniqueNumbers = removeDuplicates(numbers);
        printArray(uniqueNumbers);
        // 期待する出力: 1, 2, 3, 4, 5
    }

    // removeDuplicates メソッドを実装してください。
    public static int[] removeDuplicates(int[] arr) {
        int[] temp = new int[arr.length];
        int j = 0;
        for (int i = 0; i < arr.length; i++) {
            boolean isDuplicate = false;
            for (int k = 0; k < i; k++) {
                if (arr[i] == temp[k]) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                temp[j++] = arr[i];
            }
        }
        int[] uniqueArr = new int[j];
        for (int i = 0; i < j; i++) {
            uniqueArr[i] = temp[i];
        }
        return uniqueArr;
    }
    // printArray メソッドを実装してください。
    public static void printArray(int[] numbers) {
        for (int i = 0; i < numbers.length-1; i++) {
            System.out.printf("%d, ", numbers[i]);
        }
        System.out.printf("%d", numbers[numbers.length-1]);
    }
    // これらのメソッドでfor文とif文を使用すること。
}
0
0
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
0