制御構文とメソッドの基礎
本記事では、Javaにおける条件分岐、ループ、ジャンプ制御、メソッド定義の基本を整理する。特にswitch文の振る舞いとfor/whileの使い分け、メソッドのオーバーロードに焦点を当てる。
switch文
基本構文
switch(式){
case 定数値1:
処理1;
break;
case 定数値2:
処理2;
break;
default:
デフォルト処理;
break;
}
- 式に使用可能な型:byte、short、int、char(JDK5以降はenum、JDK7以降はString)
- caseの値はコンパイル時定数である必要があり、同一switch内で重複不可
- break文がない場合、後続のcaseやdefaultの処理が実行される(フォールスルー)
- defaultは必須ではなく、位置もswitchブロック内の任意の場所に記述可能
フォールスルーを活用した例:飲料購入シミュレーション
import java.util.Scanner;
public class DrinkSelector {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("価格を入力:");
int price = scanner.nextInt();
switch (price) {
case 3:
System.out.println("コーラを購入");
break;
case 6:
System.out.println("ミオドンを購入");
break;
case 5:
System.out.println("ウォンツァイを購入");
break;
case 14:
System.out.println("ホエユアンを購入");
break;
case 8:
System.out.println("ココナッツジュースを購入");
break;
default:
System.out.println("該当する飲料がありません");
}
scanner.close();
}
}
フォールスルーの動作確認
public class FallThroughTest {
public static void main(String[] args) {
int x = 2;
int y = 3;
switch (x) {
default:
y++;
break;
case 3:
y++;
case 4:
y++;
}
System.out.println("y=" + y); // 4(breakにより終了)
}
}
breakを省略した場合:
public class FallThroughTest2 {
public static void main(String[] args) {
int x = 2;
int y = 3;
switch (x) {
default:
y++;
case 3:
y++;
case 4:
y++;
}
System.out.println("y=" + y); // 6(フォールスルーにより全実行)
}
}
フォールスルーを利用した選択問題の簡略化
Scanner sc = new Scanner(System.in);
System.out.println("問題:リレーショナルデータベースはどれ?");
System.out.println("A. Redis B. ClickHouse C. MySQL D. HBase");
String ans = sc.next();
switch (ans) {
case "A":
case "B":
case "D":
System.out.println("不正解");
break;
case "C":
System.out.println("正解");
break;
}
ループ構文
whileループ
基本構文
初期化;
while (条件式) {
ループ処理;
更新処理;
}
演習:紙の折り畳みと富士山の高さ
public class FoldPaper {
public static void main(String[] args) {
int mountainHeightCm = 884800; // 8848mをcmに換算
int thickness = 1; // 0.01m = 1cm
int count = 0;
while (thickness < mountainHeightCm) {
count++;
thickness *= 2;
}
System.out.println(count + "回で達成");
System.out.println("最終厚さ:" + (thickness / 100.0) + "m");
}
}
// 出力:20回、10485.76m
forループ
基本構文
for (初期化; 条件式; 更新処理) {
ループ処理;
}
補足:
- 初期化はループ開始時に1度のみ実行
- 条件式を省略すると無限ループ(for(;;))
演習例:各種計算
public class LoopExercises {
public static void main(String[] args) {
// 1から10の合計
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("合計:" + sum);
// 1から100までの偶数の合計
int evenSum = 0;
for (int i = 2; i <= 100; i += 2) {
evenSum += i;
}
System.out.println("偶数の合計:" + evenSum);
// 5の階乗
int fact = 1;
for (int i = 1; i <= 5; i++) {
fact *= i;
}
System.out.println("5の階乗:" + fact);
}
}
水仙花数の検出
public class NarcissisticNumbers {
public static void main(String[] args) {
int count = 0;
for (int i = 100; i <= 999; i++) {
int a = i / 100;
int b = (i / 10) % 10;
int c = i % 10;
if (a*a*a + b*b*b + c*c*c == i) {
System.out.println(i);
count++;
}
}
System.out.println("水仙花数は" + count + "個");
}
}
二重ループ:九九の表
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i + "×" + j + "=" + (i*j) + "\t");
}
System.out.println();
}
}
}
do-whileループ
初期化;
do {
ループ処理;
更新処理;
} while (条件式);
do-whileは条件に関わらず最低1回はループ処理を実行する。
ジャンプ制御文
- break:ループやswitchブロックを強制終了
- continue:現在のループイテレーションをスキップし、次のイテレーションへ
- return:メソッドの実行を終了し、呼び出し元に制御を戻す(戻り値がある場合はその値を返す)
メソッド
基本構文
public static 戻り値の型 メソッド名(引数リスト) {
メソッド本体;
return 戻り値;
}
注意点:
- メソッドはクラス内で定義し、入れ子は不可
- 戻り値がある場合、return文は必須
- 戻り値がない場合はvoidを使用
オーバーロード
同じメソッド名でも引数の型や数が異なる場合、別のメソッドとして定義可能。
public class OverloadExample {
public static int add(int a, int b) {
return a + b;
}
public static long add(int x, long y, int z) {
return x + y + z;
}
public static void main(String[] args) {
System.out.println(add(3, 4)); // int版
System.out.println(add(3, 10L, 5)); // long版
}
}
演習:最大値の判定
import java.util.Scanner;
public class MaxComparer {
public static void compare(int a, int b) {
if (a > b) {
System.out.println("最大値:" + a);
} else {
System.out.println("最大値:" + b);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("数値1:");
int x = sc.nextInt();
System.out.print("数値2:");
int y = sc.nextInt();
compare(x, y);
sc.close();
}
}
演習:指定サイズの星形出力
public class StarPrinter {
public static void printStar(int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("*\t");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("行数:");
int r = sc.nextInt();
System.out.print("列数:");
int c = sc.nextInt();
printStar(r, c);
sc.close();
}
}