Java 抽象クラス


abstract class Score {
  private String subject;
  protected int score;

  Score(String subject, int score) {
    this.subject = subject;
    this.score = score;
  }

  protected abstract String getResult();

  String getScoreString() {
    return this.subject + ", " + this.score + ", " + this.getResult();
  }
}

class MathScore extends Score {
  MathScore(int score) {
    super("Math", score);
  }

  @Override
  protected String getResult() {
    System.out.println("MathScore method");
    return this.score >= 50 ? "Pass" : "Fail";
  }
}

class EnglishScore extends Score {
  EnglishScore(int score) {
    super("English", score);
  }

  @Override
  protected String getResult() {
    System.out.println("EnglishScore method");
    return this.score >= 70 ? "Pass" : "Fail";
  }
}

class User {
  private String name;
  private Score score;

  User(String name, Score score) {
    this.name = name;
    this.score = score;
  }

  String getUserString() {
    return this.name + ", " + this.score.getScoreString();
  }
}

public class MyApp {
  public static void main(String[] args) {
    User user1 = new User("Taro", new MathScore(70));
    User user2 = new User("Jiro", new EnglishScore(80));

    System.out.println(user1.getUserString());
    System.out.println(user2.getUserString());
  }
}

Java TodoList


import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

class TodoItem implements Serializable {
    private static final long serialVersionUID = 1L;
    private static int counter = 1;
    private int id;
    private String description;
    private String category;
    private Date deadline;
    private String priority;
    private boolean completed;

    public TodoItem(String description, String category, String deadline, String priority) throws ParseException {
        this.id = counter++;
        this.description = description;
        this.category = category;
        this.deadline = new SimpleDateFormat("yyyy-MM-dd").parse(deadline);
        this.priority = priority;
        this.completed = false;
    }

    public int getId() {
        return id;
    }

    public String getDescription() {
        return description;
    }

    public String getCategory() {
        return category;
    }

    public Date getDeadline() {
        return deadline;
    }

    public String getPriority() {
        return priority;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void markCompleted() {
        this.completed = true;
    }

    public boolean isOverdue() {
        return !completed && deadline.before(new Date());
    }

    @Override
    public String toString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String status = isCompleted() ? "完了" : (isOverdue() ? "期限切れ" : "未完了");
        return String.format("%-4d %-30s %-15s %-10s %-10s %-10s",
                id, description, category, priority, sdf.format(deadline), status);
    }
}

public class TodoListApp {
    private Map<String, List<TodoItem>> userTasks = new HashMap<>();
    private static final String DATA_FILE = "todo_data.ser";
    private String currentUser = "default";

    public TodoListApp() {
        loadTasks();
    }

    public void addTask(String description, String category, String deadline, String priority) {
        try {
            userTasks.computeIfAbsent(currentUser, k -> new ArrayList<>())
                     .add(new TodoItem(description, category, deadline, priority));
            System.out.println("タスクを追加しました。");
            saveTasks();
        } catch (ParseException e) {
            System.out.println("無効な日付形式です。形式 yyyy-MM-dd");
        }
    }

    public void listTasks() {
        List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
        if (tasks.isEmpty()) {
            System.out.println("タスクがありません。");
            return;
        }

        System.out.println(String.format("%-4s %-30s %-15s %-10s %-10s %-10s",
                "ID", "タスク内容", "カテゴリ", "優先度", "期限", "状態"));
        tasks.stream()
             .sorted(Comparator.comparing(TodoItem::getDeadline).thenComparing(TodoItem::getPriority))
             .forEach(System.out::println);
    }

    public void markTaskCompleted(int id) {
        List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
        for (TodoItem task : tasks) {
            if (task.getId() == id) {
                task.markCompleted();
                System.out.println("タスクを完了しました。");
                saveTasks();
                return;
            }
        }
        System.out.println("タスクが見つかりません。");
    }

    public void removeTask(int id) {
        List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
        if (tasks.removeIf(task -> task.getId() == id)) {
            System.out.println("タスクを削除しました。");
            saveTasks();
        } else {
            System.out.println("タスクが見つかりません。");
        }
    }

    private void saveTasks() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_FILE))) {
            oos.writeObject(userTasks);
        } catch (IOException e) {
            System.out.println("タスクの保存に失敗しました。");
        }
    }

    @SuppressWarnings("unchecked")
    private void loadTasks() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(DATA_FILE))) {
            userTasks = (Map<String, List<TodoItem>>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("以前のタスクを読み込めませんでした。");
        }
    }

    public static void main(String[] args) {
        TodoListApp app = new TodoListApp();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\nTODOリスト - " + app.currentUser);
            System.out.println("1. タスクを追加");
            System.out.println("2. タスクを一覧表示");
            System.out.println("3. タスクを完了済みにする");
            System.out.println("4. タスクを削除");
            System.out.println("5. 終了");
            System.out.print("選択してください: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 改行を消費

            switch (choice) {
                case 1:
                    System.out.print("タスク内容: ");
                    String description = scanner.nextLine();
                    System.out.print("カテゴリ: ");
                    String category = scanner.nextLine();
                    System.out.print("期限 (yyyy-MM-dd): ");
                    String deadline = scanner.nextLine();
                    System.out.print("優先度 (高, 中, 低): ");
                    String priority = scanner.nextLine();
                    app.addTask(description, category, deadline, priority);
                    break;
                case 2:
                    app.listTasks();
                    break;
                case 3:
                    System.out.print("完了するタスクのID: ");
                    int completeId = scanner.nextInt();
                    app.markTaskCompleted(completeId);
                    break;
                case 4:
                    System.out.print("削除するタスクのID: ");
                    int removeId = scanner.nextInt();
                    app.removeTask(removeId);
                    break;
                case 5:
                    System.out.println("終了します。");
                    scanner.close();
                    return;
                default:
                    System.out.println("無効な選択です。");
            }
        }
    }
}

javac -encoding UTF-8 TodoListApp.java
java TodoListApp

Java クラス変数

class User {
  String name;
  int score;
  static int count = 0;

  User(String name, int score) {
    this.name = name;
    this.score = score;
    User.count++;
  }
}

public class MyApp {
  public static void main(String[] args) {
    // int count = 0;
    User user1 = new User("Taro", 70);
    // count++;
    User user2 = new User("Jiro", 80);
    // count++;

    // System.out.println(count);
    System.out.println(User.count);
  }
}

Java メソッド

public class MyApp {
  private static void showAd() {
    System.out.println("---------");
    System.out.println("SALE! 50% OFF!");
    System.out.println("---------");
  }

  private static void showContent() {
    System.out.println("BREAKING NEWS!");
    System.out.println("Two baby pandas born at our Zoo!");
  }

  public static void main(String[] args) {
    showAd();
    showContent();
    showAd();
  }
}

Java  配列と反復処理

import java.util.Scanner;

public class MyApp {
  public static void main(String[] args) {
    int[] scores = {70, 90, 80, 60};
    // System.out.println(scores[0]);
    // System.out.println(scores[1]);
    // System.out.println(scores[2]);
    // for (int i = 0; i < 3; i++) {
    for (int i = 0; i < scores.length; i++) {
      System.out.println(scores[i]);
    }
  }