はじめに
Java研修コーディング問題集の第5回は メソッド です。
メソッドはコードの再利用性を高め、プログラムを整理する基本単位です。引数・戻り値・オーバーロードなどの概念を実際にコードを書いて身につけましょう。
難易度の見方
| マーク | 難易度 | 目安 |
|---|---|---|
| ⭐ | 基本 | 研修1週目レベル |
| ⭐⭐ | 応用 | 少し考える必要あり |
| ⭐⭐⭐ | チャレンジ | 複数の知識を組み合わせる |
問題1:あいさつメソッド ⭐
問題
名前を引数に受け取り、あいさつ文を出力するメソッド greet を作成してください。
期待する出力
こんにちは、田中さん!
こんにちは、鈴木さん!
こんにちは、佐藤さん!
模範解答
public class Exercise01 {
public static void main(String[] args) {
greet("田中");
greet("鈴木");
greet("佐藤");
}
static void greet(String name) {
System.out.println("こんにちは、" + name + "さん!");
}
}
ポイント: 戻り値がないメソッドは void を指定します。同じ処理をメソッドにまとめることで、コードの重複を避けられます。
問題2:戻り値のあるメソッド ⭐
問題
2つの整数を受け取り、大きいほうの値を返すメソッド max を作成してください。
期待する出力
max(10, 20) = 20
max(55, 33) = 55
max(7, 7) = 7
模範解答
public class Exercise02 {
public static void main(String[] args) {
System.out.println("max(10, 20) = " + max(10, 20));
System.out.println("max(55, 33) = " + max(55, 33));
System.out.println("max(7, 7) = " + max(7, 7));
}
static int max(int a, int b) {
if (a >= b) {
return a;
} else {
return b;
}
}
}
ポイント: return でメソッドの呼び出し元に値を返します。戻り値の型(ここでは int)をメソッド宣言で指定します。三項演算子を使えば return a >= b ? a : b; と1行で書くこともできます。
問題3:配列を受け取るメソッド ⭐
問題
整数配列を受け取り、合計値を返すメソッド sum を作成してください。
期待する出力
{1, 2, 3, 4, 5} の合計 = 15
{10, 20, 30} の合計 = 60
模範解答
public class Exercise03 {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {10, 20, 30};
System.out.println("{1, 2, 3, 4, 5} の合計 = " + sum(arr1));
System.out.println("{10, 20, 30} の合計 = " + sum(arr2));
}
static int sum(int[] numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
}
ポイント: 配列もメソッドの引数として渡せます。Javaはすべて値渡しですが、配列は「参照の値」が渡されるため、メソッド内で配列の要素を変更すると呼び出し元にも影響します(配列そのものを差し替えることはできません)。
問題4:メソッドのオーバーロード ⭐⭐
問題
以下の3つの add メソッドをオーバーロードで作成してください。
-
intを2つ受け取り、合計を返す -
intを3つ受け取り、合計を返す -
doubleを2つ受け取り、合計を返す
期待する出力
add(3, 5) = 8
add(3, 5, 7) = 15
add(1.5, 2.3) = 3.8
模範解答
public class Exercise04 {
public static void main(String[] args) {
System.out.println("add(3, 5) = " + add(3, 5));
System.out.println("add(3, 5, 7) = " + add(3, 5, 7));
System.out.println("add(1.5, 2.3) = " + add(1.5, 2.3));
}
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
static double add(double a, double b) {
return a + b;
}
}
ポイント: オーバーロードは同じ名前のメソッドを引数の型や数を変えて複数定義することです。戻り値の型だけが異なるオーバーロードはできません。System.out.println() も実はオーバーロードされています。
問題5:可変長引数 ⭐⭐
問題
可変長引数を使って、渡された数値の中から最大値を返すメソッド findMax を作成してください。
期待する出力
最大値: 42
最大値: 99
最大値: 7
ヒント
- 可変長引数は
int... numbersのように書きます - メソッド内では配列として扱えます
模範解答
public class Exercise05 {
public static void main(String[] args) {
System.out.println("最大値: " + findMax(10, 42, 3, 27));
System.out.println("最大値: " + findMax(5, 99, 13));
System.out.println("最大値: " + findMax(7));
}
static int findMax(int... numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
}
ポイント: 可変長引数(int... numbers)を使うと、呼び出し側は任意の数の引数を渡せます。メソッド内では配列として扱われます。可変長引数はメソッドの最後の引数にのみ使えます。
問題6:再帰メソッド(階乗)⭐⭐
問題
再帰を使って、nの階乗(n!)を計算するメソッド factorial を作成してください。
- 0! = 1
- n! = n × (n-1)!
期待する出力
0! = 1
1! = 1
5! = 120
10! = 3628800
模範解答
public class Exercise06 {
public static void main(String[] args) {
System.out.println("0! = " + factorial(0));
System.out.println("1! = " + factorial(1));
System.out.println("5! = " + factorial(5));
System.out.println("10! = " + factorial(10));
}
static long factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
}
ポイント: 再帰とはメソッドが自分自身を呼び出すことです。必ず**終了条件(ベースケース)**を設定しないと無限ループ(スタックオーバーフロー)になります。階乗は数が大きくなると値が急増するため、戻り値に long を使っています。
問題7:配列を返すメソッド ⭐⭐
問題
整数配列を受け取り、偶数だけを抽出した新しい配列を返すメソッド filterEven を作成してください。
期待する出力
元の配列: [3, 8, 15, 22, 7, 10, 33, 46]
偶数のみ: [8, 22, 10, 46]
ヒント
- まず偶数の個数を数えてから、その数の配列を作成します
模範解答
public class Exercise07 {
public static void main(String[] args) {
int[] numbers = {3, 8, 15, 22, 7, 10, 33, 46};
System.out.print("元の配列: ");
printArray(numbers);
int[] evens = filterEven(numbers);
System.out.print("偶数のみ: ");
printArray(evens);
}
static int[] filterEven(int[] arr) {
// 偶数の個数を数える
int count = 0;
for (int n : arr) {
if (n % 2 == 0) count++;
}
// 偶数だけの配列を作成
int[] result = new int[count];
int index = 0;
for (int n : arr) {
if (n % 2 == 0) {
result[index] = n;
index++;
}
}
return result;
}
static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print(arr[i]);
}
System.out.println("]");
}
}
ポイント: メソッドは配列を戻り値として返すこともできます。配列のサイズは作成時に決める必要があるため、2回ループする方法を使っています。後の回で学ぶ ArrayList を使えば、動的にサイズを変えられます。
問題8:メソッド分割でリファクタリング ⭐⭐
問題
以下の処理を複数のメソッドに分割して、読みやすいコードにリファクタリングしてください。
処理内容:
- 商品リスト(名前と価格の配列)を表示
- 合計金額を計算
- 税込金額を計算(税率10%)
- 結果を表示
商品:りんご(150円)、パン(280円)、牛乳(200円)、卵(250円)
期待する出力
=== お買い物リスト ===
1. りんご: 150円
2. パン: 280円
3. 牛乳: 200円
4. 卵: 250円
---
小計: 880円
消費税(10%): 88円
合計: 968円
模範解答
public class Exercise08 {
public static void main(String[] args) {
String[] items = {"りんご", "パン", "牛乳", "卵"};
int[] prices = {150, 280, 200, 250};
System.out.println("=== お買い物リスト ===");
printItemList(items, prices);
int subtotal = calculateTotal(prices);
int tax = calculateTax(subtotal, 0.10);
int total = subtotal + tax;
System.out.println("---");
printReceipt(subtotal, tax, total);
}
static void printItemList(String[] items, int[] prices) {
for (int i = 0; i < items.length; i++) {
System.out.println((i + 1) + ". " + items[i] + ": " + prices[i] + "円");
}
}
static int calculateTotal(int[] prices) {
int total = 0;
for (int price : prices) {
total += price;
}
return total;
}
static int calculateTax(int amount, double taxRate) {
return (int) (amount * taxRate);
}
static void printReceipt(int subtotal, int tax, int total) {
System.out.println("小計: " + subtotal + "円");
System.out.println("消費税(10%): " + tax + "円");
System.out.println("合計: " + total + "円");
}
}
ポイント: 1つのメソッドに多くの処理を詰め込まず、役割ごとにメソッドを分割するのが良い設計です。各メソッドが「1つのこと」だけを行うようにすると、コードの可読性・再利用性・テスト容易性が向上します。
問題9:再帰メソッド(ハノイの塔)⭐⭐⭐
問題
ハノイの塔を再帰メソッドで解いてください。
ルール:
- 3本の棒(A, B, C)がある
- 棒Aにn枚の円盤が大きい順に積まれている
- すべての円盤を棒Cに移動する
- 一度に1枚しか移動できない
- 大きい円盤の上に小さい円盤しか置けない
n = 3 として、移動手順を出力してください。
期待する出力
=== ハノイの塔(3枚)===
円盤1: A → C
円盤2: A → B
円盤1: C → B
円盤3: A → C
円盤1: B → A
円盤2: B → C
円盤1: A → C
合計 7 回の移動
模範解答
public class Exercise09 {
static int moveCount = 0;
public static void main(String[] args) {
int n = 3;
System.out.println("=== ハノイの塔(" + n + "枚)===");
hanoi(n, 'A', 'C', 'B');
System.out.println("合計 " + moveCount + " 回の移動");
}
static void hanoi(int n, char from, char to, char via) {
if (n == 1) {
moveCount++;
System.out.println("円盤" + n + ": " + from + " → " + to);
return;
}
hanoi(n - 1, from, via, to);
moveCount++;
System.out.println("円盤" + n + ": " + from + " → " + to);
hanoi(n - 1, via, to, from);
}
}
ポイント: ハノイの塔は再帰の代表的な問題です。「n-1枚を退避→一番大きい円盤を移動→n-1枚を目的地へ」という分割統治の考え方がポイントです。n枚の場合、移動回数は 2ⁿ - 1 回になります。
問題10:ミニテストシステム ⭐⭐⭐
問題
4択クイズを出題・採点するメソッドを組み合わせたミニテストシステムを作成してください。
仕様:
- 問題文・選択肢・正解をデータとして持つ
- 各問題を表示するメソッド
- 解答をチェックするメソッド(今回は自動回答で動作確認)
- 結果を集計・表示するメソッド
期待する出力
=== Java ミニテスト ===
【問題1】Javaのエントリーポイントとなるメソッドは?
A: start B: main C: run D: init
→ 回答: B → ○
【問題2】int型のデフォルト値は?
A: null B: 1 C: 0 D: -1
→ 回答: C → ○
【問題3】配列の要素数を取得するプロパティは?
A: size B: count C: length D: total
→ 回答: C → ○
=== 結果 ===
正解数: 3 / 3
スコア: 100.0%
評価: 満点!
模範解答
public class Exercise10 {
public static void main(String[] args) {
// 問題データ
String[] questions = {
"Javaのエントリーポイントとなるメソッドは?",
"int型のデフォルト値は?",
"配列の要素数を取得するプロパティは?"
};
String[][] choices = {
{"start", "main", "run", "init"},
{"null", "1", "0", "-1"},
{"size", "count", "length", "total"}
};
int[] answers = {1, 2, 2}; // 正解のインデックス(0始まり)
int[] userAnswers = {1, 2, 2}; // 自動回答(テスト用)
System.out.println("=== Java ミニテスト ===");
int correctCount = 0;
for (int i = 0; i < questions.length; i++) {
printQuestion(i + 1, questions[i], choices[i]);
boolean isCorrect = checkAnswer(userAnswers[i], answers[i]);
printResult(userAnswers[i], isCorrect);
if (isCorrect) correctCount++;
}
printSummary(correctCount, questions.length);
}
static void printQuestion(int number, String question, String[] choices) {
System.out.println("\n【問題" + number + "】" + question);
System.out.print(" ");
char label = 'A';
for (int i = 0; i < choices.length; i++) {
if (i > 0) System.out.print(" ");
System.out.print(label + ": " + choices[i]);
label++;
}
System.out.println();
}
static boolean checkAnswer(int userAnswer, int correctAnswer) {
return userAnswer == correctAnswer;
}
static void printResult(int answerIndex, boolean isCorrect) {
char label = (char) ('A' + answerIndex);
System.out.println("→ 回答: " + label + " → " + (isCorrect ? "○" : "×"));
}
static void printSummary(int correct, int total) {
double score = (double) correct / total * 100;
String grade;
if (score == 100) {
grade = "満点!";
} else if (score >= 70) {
grade = "合格!";
} else {
grade = "もう少し頑張りましょう";
}
System.out.println("\n=== 結果 ===");
System.out.println("正解数: " + correct + " / " + total);
System.out.println("スコア: " + String.format("%.1f", score) + "%");
System.out.println("評価: " + grade);
}
}
ポイント: メソッドを適切に分割することで、各メソッドの責務が明確になります。データ(問題・選択肢・正解)と処理(表示・判定・集計)を分離する考え方は、オブジェクト指向プログラミングの基礎にもつながります。
まとめ
| 問題 | テーマ | 難易度 |
|---|---|---|
| 問題1 | void メソッド | ⭐ |
| 問題2 | 戻り値のあるメソッド | ⭐ |
| 問題3 | 配列を受け取るメソッド | ⭐ |
| 問題4 | メソッドのオーバーロード | ⭐⭐ |
| 問題5 | 可変長引数 | ⭐⭐ |
| 問題6 | 再帰メソッド(階乗) | ⭐⭐ |
| 問題7 | 配列を返すメソッド | ⭐⭐ |
| 問題8 | メソッド分割リファクタリング | ⭐⭐ |
| 問題9 | 再帰(ハノイの塔) | ⭐⭐⭐ |
| 問題10 | ミニテストシステム(総合問題) | ⭐⭐⭐ |
次回は 文字列操作(String) のコーディング問題です!
シリーズ一覧:Java研修コーディング問題集
- 変数・データ型・演算子 編
- 条件分岐(if / switch)編
- 繰り返し処理(for / while)編
- 配列 編
- 👉 メソッド 編(本記事)
- 文字列操作(String)編
- クラスとオブジェクト 編
- 継承とインターフェース 編
- 例外処理 編
- コレクションと Stream API 編
著者: @kotaro_ai_lab
AI駆動開発やテック情報を毎日発信しています。フォローお気軽にどうぞ!