Java ペイントソフト

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Stack;
import javax.imageio.ImageIO;
import java.io.File;

public class AdvancedPaintAppWithUndoRedo extends JFrame {

    private DrawPanel drawPanel;
    private Color currentColor = Color.BLACK;
    private int brushSize = 4;
    private String currentTool = "Brush";
    private Stack<BufferedImage> undoStack = new Stack<>();
    private Stack<BufferedImage> redoStack = new Stack<>();

    public AdvancedPaintAppWithUndoRedo() {
        setTitle("Advanced Paint Application with Undo/Redo");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        drawPanel = new DrawPanel();
        add(drawPanel, BorderLayout.CENTER);

        // メニューバーの作成
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        JMenuItem saveItem = new JMenuItem("Save");
        JMenuItem openItem = new JMenuItem("Open");
        JMenuItem clearItem = new JMenuItem("Clear");
        saveItem.addActionListener(e -> saveImage());
        openItem.addActionListener(e -> openImage());
        clearItem.addActionListener(e -> drawPanel.clearCanvas());
        fileMenu.add(saveItem);
        fileMenu.add(openItem);
        fileMenu.add(clearItem);
        menuBar.add(fileMenu);

        JMenu toolMenu = new JMenu("Tools");
        JMenuItem colorItem = new JMenuItem("Choose Color");
        JMenuItem brushItem = new JMenuItem("Brush Size");
        JMenuItem toolBrush = new JMenuItem("Brush");
        JMenuItem toolLine = new JMenuItem("Line");
        JMenuItem toolRect = new JMenuItem("Rectangle");
        JMenuItem toolOval = new JMenuItem("Oval");
        JMenuItem toolText = new JMenuItem("Text");

        colorItem.addActionListener(e -> chooseColor());
        brushItem.addActionListener(e -> chooseBrushSize());
        toolBrush.addActionListener(e -> currentTool = "Brush");
        toolLine.addActionListener(e -> currentTool = "Line");
        toolRect.addActionListener(e -> currentTool = "Rectangle");
        toolOval.addActionListener(e -> currentTool = "Oval");
        toolText.addActionListener(e -> currentTool = "Text");

        toolMenu.add(colorItem);
        toolMenu.add(brushItem);
        toolMenu.add(toolBrush);
        toolMenu.add(toolLine);
        toolMenu.add(toolRect);
        toolMenu.add(toolOval);
        toolMenu.add(toolText);
        menuBar.add(toolMenu);

        JMenu editMenu = new JMenu("Edit");
        JMenuItem undoItem = new JMenuItem("Undo");
        JMenuItem redoItem = new JMenuItem("Redo");
        undoItem.addActionListener(e -> drawPanel.undo());
        redoItem.addActionListener(e -> drawPanel.redo());
        editMenu.add(undoItem);
        editMenu.add(redoItem);
        menuBar.add(editMenu);

        setJMenuBar(menuBar);
    }

    // メインメソッド
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            AdvancedPaintAppWithUndoRedo app = new AdvancedPaintAppWithUndoRedo();
            app.setVisible(true);
        });
    }

    // 色を選択する
    private void chooseColor() {
        Color color = JColorChooser.showDialog(null, "Choose a Color", currentColor);
        if (color != null) {
            currentColor = color;
            drawPanel.setColor(color);
        }
    }

    // ブラシサイズを選択する
    private void chooseBrushSize() {
        String sizeStr = JOptionPane.showInputDialog(this, "Enter brush size:", brushSize);
        if (sizeStr != null) {
            try {
                int size = Integer.parseInt(sizeStr);
                if (size > 0) {
                    brushSize = size;
                    drawPanel.setBrushSize(size);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "Invalid size entered.");
            }
        }
    }

    // 画像を保存する
    private void saveImage() {
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                ImageIO.write(drawPanel.getImage(), "png", file);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // 画像を開く
    private void openImage() {
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                BufferedImage image = ImageIO.read(file);
                drawPanel.setImage(image);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // 描画用のパネル
    class DrawPanel extends JPanel {

        private BufferedImage image;
        private Graphics2D g2;
        private int startX, startY, endX, endY;

        public DrawPanel() {
            setPreferredSize(new Dimension(800, 600));
            setDoubleBuffered(false);
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    startX = e.getX();
                    startY = e.getY();
                    if (g2 != null) {
                        if (currentTool.equals("Brush")) {
                            g2.fillOval(startX, startY, brushSize, brushSize);
                        }
                        saveToUndoStack();
                    }
                    repaint();
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    endX = e.getX();
                    endY = e.getY();
                    if (g2 != null) {
                        switch (currentTool) {
                            case "Line":
                                g2.drawLine(startX, startY, endX, endY);
                                break;
                            case "Rectangle":
                                g2.drawRect(Math.min(startX, endX), Math.min(startY, endY),
                                        Math.abs(startX - endX), Math.abs(startY - endY));
                                break;
                            case "Oval":
                                g2.drawOval(Math.min(startX, endX), Math.min(startY, endY),
                                        Math.abs(startX - endX), Math.abs(startY - endY));
                                break;
                            case "Text":
                                String text = JOptionPane.showInputDialog("Enter text:");
                                if (text != null) {
                                    g2.drawString(text, startX, startY);
                                }
                                break;
                        }
                    }
                    saveToUndoStack();
                    repaint();
                }
            });

            addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseDragged(MouseEvent e) {
                    if (currentTool.equals("Brush")) {
                        g2.fillOval(e.getX(), e.getY(), brushSize, brushSize);
                    }
                    repaint();
                }
            });

            clearCanvas();
        }

        // Undoスタックに現在の状態を保存
        private void saveToUndoStack() {
            BufferedImage undoImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
            Graphics2D g = undoImage.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            undoStack.push(undoImage);
            redoStack.clear();  // 新しいアクションの後、Redoをクリア
        }

        // Undo機能
        public void undo() {
            if (!undoStack.isEmpty()) {
                redoStack.push(image);
                image = undoStack.pop();
                g2 = image.createGraphics();
                repaint();
            }
        }

        // Redo機能
        public void redo() {
            if (!redoStack.isEmpty()) {
                undoStack.push(image);
                image = redoStack.pop();
                g2 = image.createGraphics();
                repaint();
            }
        }

        // 色を設定
        public void setColor(Color color) {
            if (g2 != null) {
                g2.setColor(color);
            }
        }

        // ブラシサイズを設定
        public void setBrushSize(int size) {
            brushSize = size;
        }

        // キャンバスをクリア
        public void clearCanvas() {
            image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
            g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.WHITE);
            g2.fillRect(0, 0, image.getWidth(), image.getHeight());
            g2.setPaint(Color.BLACK);
            repaint();
        }

        // 描画イメージを取得
        public BufferedImage getImage() {
            return image;
        }

        // 描画イメージをセット
        public void setImage(BufferedImage img) {
            image = img;
            g2 = image.createGraphics();
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (image != null) {
                g.drawImage(image, 0, 0, null);
            }
        }
    }
}

Java テキストエディタ

import javax.swing.*;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;

public class AdvancedTextEditor extends JFrame implements ActionListener {
    JTabbedPane tabbedPane;
    JTextArea textArea;
    JMenuBar menuBar;
    JMenu fileMenu, editMenu, formatMenu, themeMenu;
    JMenuItem newItem, openItem, saveItem, saveAllItem, closeItem;
    JMenuItem cutItem, copyItem, pasteItem, findItem, replaceItem, undoItem, redoItem;
    JMenuItem fontItem, lightThemeItem, darkThemeItem;
    JFileChooser fileChooser;
    JLabel statusBar;
    UndoManager undoManager = new UndoManager();
    JPopupMenu contextMenu;

    public AdvancedTextEditor() {
        setTitle("Advanced Text Editor");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        tabbedPane = new JTabbedPane();
        add(tabbedPane, BorderLayout.CENTER);

        statusBar = new JLabel("Status: Ready | Line: 1, Column: 1");
        add(statusBar, BorderLayout.SOUTH);

        menuBar = new JMenuBar();

        // ファイルメニューの作成
        fileMenu = new JMenu("File");
        newItem = new JMenuItem("New");
        openItem = new JMenuItem("Open");
        saveItem = new JMenuItem("Save");
        saveAllItem = new JMenuItem("Save All");
        closeItem = new JMenuItem("Close");
        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(saveAllItem);
        fileMenu.add(closeItem);

        // 編集メニューの作成
        editMenu = new JMenu("Edit");
        cutItem = new JMenuItem("Cut");
        copyItem = new JMenuItem("Copy");
        pasteItem = new JMenuItem("Paste");
        undoItem = new JMenuItem("Undo");
        redoItem = new JMenuItem("Redo");
        findItem = new JMenuItem("Find");
        replaceItem = new JMenuItem("Replace");
        editMenu.add(cutItem);
        editMenu.add(copyItem);
        editMenu.add(pasteItem);
        editMenu.add(undoItem);
        editMenu.add(redoItem);
        editMenu.add(findItem);
        editMenu.add(replaceItem);

        // フォーマットメニューの作成
        formatMenu = new JMenu("Format");
        fontItem = new JMenuItem("Change Font");
        formatMenu.add(fontItem);

        // テーマメニューの作成
        themeMenu = new JMenu("Themes");
        lightThemeItem = new JMenuItem("Light Theme");
        darkThemeItem = new JMenuItem("Dark Theme");
        themeMenu.add(lightThemeItem);
        themeMenu.add(darkThemeItem);

        // メニューバーにメニューを追加
        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(formatMenu);
        menuBar.add(themeMenu);

        setJMenuBar(menuBar);

        // アクションリスナーの設定
        newItem.addActionListener(this);
        openItem.addActionListener(this);
        saveItem.addActionListener(this);
        saveAllItem.addActionListener(this);
        closeItem.addActionListener(this);
        cutItem.addActionListener(this);
        copyItem.addActionListener(this);
        pasteItem.addActionListener(this);
        undoItem.addActionListener(this);
        redoItem.addActionListener(this);
        findItem.addActionListener(this);
        replaceItem.addActionListener(this);
        fontItem.addActionListener(this);
        lightThemeItem.addActionListener(this);
        darkThemeItem.addActionListener(this);

        // ドラッグ&ドロップ対応
        new DropTarget(tabbedPane, new FileDropHandler());

        // コンテキストメニューの設定
        contextMenu = new JPopupMenu();
        contextMenu.add(cutItem);
        contextMenu.add(copyItem);
        contextMenu.add(pasteItem);
    }

    // アクションリスナーの処理
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == newItem) {
            addNewTab();
        }
        // 他のアクションもここに追加
    }

    // 新しいタブを追加するメソッド
    private void addNewTab() {
        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        tabbedPane.add("Untitled", scrollPane);
        tabbedPane.setSelectedComponent(scrollPane);
        textArea.getDocument().addUndoableEditListener(e -> undoManager.addEdit(e.getEdit()));
    }

    // ファイルドロップハンドラ
    @SuppressWarnings("unchecked")
    class FileDropHandler extends DropTargetAdapter {
        @Override
        public void drop(DropTargetDropEvent dtde) {
            dtde.acceptDrop(DnDConstants.ACTION_COPY);
            try {
                java.util.List<File> droppedFiles = (java.util.List<File>) dtde.getTransferable()
                        .getTransferData(DataFlavor.javaFileListFlavor);
                for (File file : droppedFiles) {
                    openFile(file);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // ファイルを開くメソッド
    private void openFile(File file) {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            JTextArea textArea = new JTextArea();
            textArea.read(reader, null);
            JScrollPane scrollPane = new JScrollPane(textArea);
            tabbedPane.add(file.getName(), scrollPane);
            tabbedPane.setSelectedComponent(scrollPane);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            AdvancedTextEditor editor = new AdvancedTextEditor();
            editor.setVisible(true);
        });
    }
}

Java シンプルRPG

簡単なRPGを作成するために、以下のコードを提供します。このコードは、プレイヤーキャラクターと敵キャラクターが戦うシンプルなテキストベースのRPGです。

java
Copy code
import java.util.Scanner;

public class SimpleRPG {

    // キャラクタークラス
    public static class Character {
        private String name;
        private int health;
        private int attackPower;

        public Character(String name, int health, int attackPower) {
            this.name = name;
            this.health = health;
            this.attackPower = attackPower;
        }

        public String getName() {
            return name;
        }

        public int getHealth() {
            return health;
        }

        public void setHealth(int health) {
            this.health = health;
        }

        public int getAttackPower() {
            return attackPower;
        }

        public void attack(Character enemy) {
            System.out.println(name + " attacks " + enemy.getName() + " for " + attackPower + " damage.");
            enemy.setHealth(enemy.getHealth() - attackPower);
        }
    }

    // メインメソッド
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // プレイヤーキャラクターの作成
        Character player = new Character("Player", 100, 20);
        Character enemy = new Character("Goblin", 50, 10);

        System.out.println("A wild " + enemy.getName() + " appears!");

        // 戦闘ループ
        while (player.getHealth() > 0 && enemy.getHealth() > 0) {
            System.out.println("Your HP: " + player.getHealth());
            System.out.println(enemy.getName() + " HP: " + enemy.getHealth());
            System.out.println("1. Attack");
            System.out.println("2. Run");
            int choice = scanner.nextInt();

            if (choice == 1) {
                player.attack(enemy);
                if (enemy.getHealth() > 0) {
                    enemy.attack(player);
                } else {
                    System.out.println("You defeated the " + enemy.getName() + "!");
                }
            } else if (choice == 2) {
                System.out.println("You ran away!");
                break;
            }

            if (player.getHealth() <= 0) {
                System.out.println("You were defeated by the " + enemy.getName() + "...");
            }
        }

        scanner.close();
    }
}
このコードをテキストエディタにコピーして、SimpleRPG.javaとして保存してください。次に、以下のコマンドを使ってコンパイルし、実行してください。

sh
Copy code
javac SimpleRPG.java
java SimpleRPG
このコードは、プレイヤーが敵と戦うシンプルなRPGです。プレイヤーは敵を攻撃するか、逃げるかを選択できます。戦闘が進むにつれて、各キャラクターのHPが減少し、最終的に勝敗が決まります。






Java 電卓

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {
    private JTextField display;
    private JPanel panel;
    private StringBuilder currentInput;
    private double result;
    private String operator;

    public Calculator() {
        // Frame settings
        setTitle("Calculator");
        setSize(400, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Display settings
        display = new JTextField();
        display.setEditable(false);
        display.setFont(new Font("Arial", Font.BOLD, 24));
        add(display, BorderLayout.NORTH);

        // Button panel settings
        panel = new JPanel();
        panel.setLayout(new GridLayout(4, 4));

        // Create and add buttons
        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        };

        for (String text : buttons) {
            JButton button = new JButton(text);
            button.setFont(new Font("Arial", Font.BOLD, 24));
            button.addActionListener(this);
            panel.add(button);
        }

        add(panel, BorderLayout.CENTER);

        currentInput = new StringBuilder();
        result = 0;
        operator = "";
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();

        if ("0123456789.".contains(command)) {
            currentInput.append(command);
            display.setText(currentInput.toString());
        } else if (command.equals("=")) {
            calculate();
            display.setText(String.valueOf(result));
            currentInput.setLength(0);
        } else {
            if (currentInput.length() > 0) {
                calculate();
                operator = command;
                display.setText(String.valueOf(result));
                currentInput.setLength(0);
            }
        }
    }

    private void calculate() {
        double input = currentInput.length() > 0 ? Double.parseDouble(currentInput.toString()) : 0;

        switch (operator) {
            case "+":
                result += input;
                break;
            case "-":
                result -= input;
                break;
            case "*":
                result *= input;
                break;
            case "/":
                result /= input;
                break;
            default:
                result = input;
                break;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Calculator calculator = new Calculator();
            calculator.setVisible(true);
        });
    }
}
  1. javac Calculator.java
  2. java Calculator

Java メモ帳

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class SimpleNotepad extends JFrame implements ActionListener {
    private JTextArea textArea;
    private JMenuItem openItem, saveItem, exitItem;

    public SimpleNotepad() {
        // Frame settings
        setTitle("Simple Notepad");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Text area settings
        textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane, BorderLayout.CENTER);

        // Menu bar creation
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        openItem = new JMenuItem("Open");
        saveItem = new JMenuItem("Save");
        exitItem = new JMenuItem("Exit");

        openItem.addActionListener(this);
        saveItem.addActionListener(this);
        exitItem.addActionListener(this);

        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(exitItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == openItem) {
            openFile();
        } else if (e.getSource() == saveItem) {
            saveFile();
        } else if (e.getSource() == exitItem) {
            System.exit(0);
        }
    }

    private void openFile() {
        JFileChooser fileChooser = new JFileChooser();
        int option = fileChooser.showOpenDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try (BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()))) {
                textArea.read(reader, null);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "File could not be opened", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void saveFile() {
        JFileChooser fileChooser = new JFileChooser();
        int option = fileChooser.showSaveDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try (FileWriter writer = new FileWriter(fileChooser.getSelectedFile())) {
                textArea.write(writer);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "File could not be saved", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SimpleNotepad notepad = new SimpleNotepad();
            notepad.setVisible(true);
        });
    }
}

java 数当てゲーム

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean playAgain = true;
        int highScore = 0;

        System.out.println("数当てゲームへようこそ!");

        while (playAgain) {
            int minRange = 1;
            int maxRange = 100;
            int randomNumber = (int) (Math.random() * (maxRange - minRange + 1)) + minRange;
            int attempts = 0;

            System.out.println("1から100までの数を当ててください!");

            while (true) {
                System.out.print("予想した数字を入力してください: ");
                if (!scanner.hasNextInt()) {
                    System.out.println("無効な入力です。数値を入力してください。");
                    scanner.next(); // 不正な入力をクリア
                    continue;
                }
                int guessedNumber = scanner.nextInt();
                attempts++;

                if (guessedNumber < randomNumber) {
                    System.out.println("もっと大きい数字です。");
                } else if (guessedNumber > randomNumber) {
                    System.out.println("もっと小さい数字です。");
                } else {
                    System.out.println("おめでとうございます!正解です!");
                    System.out.println("あなたの試行回数: " + attempts);
                    if (attempts < highScore || highScore == 0) {
                        highScore = attempts;
                        System.out.println("新しいハイスコア!試行回数: " + highScore);
                    } else {
                        System.out.println("ハイスコアは" + highScore + "回です。");
                    }
                    break;
                }
            }

            System.out.print("もう一度プレイしますか? (y/n): ");
            String playChoice = scanner.next();
            playAgain = playChoice.equalsIgnoreCase("y");
        }

        System.out.println("ゲームを終了します。");
        System.out.println("最終ハイスコア: " + highScore);
        scanner.close();
    }
}

Java タスク管理

package sample;
import java.util.ArrayList;
import java.util.Scanner;

public class TaskManager {
    private static ArrayList<Task> tasks = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        boolean running = true;

        while (running) {
            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:
                    addTask();
                    break;
                case 2:
                    deleteTask();
                    break;
                case 3:
                    displayTasks();
                    break;
                case 4:
                    changeTaskStatus();
                    break;
                case 5:
                    running = false;
                    break;
                default:
                    System.out.println("無効な選択です。");
            }
        }

        scanner.close();
    }

    private static void addTask() {
        System.out.print("タスクの名前を入力してください: ");
        String name = scanner.nextLine();
        System.out.print("タスクの期限を入力してください (例: YYYY-MM-DD): ");
        String deadline = scanner.nextLine();
        System.out.print("タスクの優先度を入力してください (高/中/低): ");
        String priority = scanner.nextLine();
        tasks.add(new Task(name, deadline, priority));
        System.out.println("タスクを追加しました。");
    }

    private static void deleteTask() {
        if (tasks.isEmpty()) {
            System.out.println("削除するタスクはありません。");
            return;
        }

        System.out.println("削除するタスクを選択してください:");
        displayTasks();
        System.out.print("削除するタスクの番号を入力してください: ");
        int index = scanner.nextInt();
        scanner.nextLine(); // 改行を読み飛ばす

        if (index < 1 || index > tasks.size()) {
            System.out.println("無効な番号です。");
        } else {
            Task deletedTask = tasks.remove(index - 1);
            System.out.println(deletedTask.getName() + " を削除しました。");
        }
    }

    private static void displayTasks() {
        if (tasks.isEmpty()) {
            System.out.println("タスクはありません。");
        } else {
            System.out.println("現在のタスク:");
            for (int i = 0; i < tasks.size(); i++) {
                System.out.println((i + 1) + ". " + tasks.get(i));
            }
        }
    }

    private static void changeTaskStatus() {
        if (tasks.isEmpty()) {
            System.out.println("タスクはありません。");
            return;
        }

        System.out.println("状態を変更するタスクを選択してください:");
        displayTasks();
        System.out.print("状態を変更するタスクの番号を入力してください: ");
        int index = scanner.nextInt();
        scanner.nextLine(); // 改行を読み飛ばす

        if (index < 1 || index > tasks.size()) {
            System.out.println("無効な番号です。");
        } else {
            Task task = tasks.get(index - 1);
            System.out.print("新しい状態を入力してください (未完了/進行中/完了): ");
            String newStatus = scanner.nextLine();
            task.setStatus(newStatus);
            System.out.println(task.getName() + " の状態を " + newStatus + " に変更しました。");
        }
    }
}

class Task {
    private String name;
    private String deadline;
    private String priority;
    private String status = "未完了"; // デフォルトの状態は未完了

    public Task(String name, String deadline, String priority) {
        this.name = name;
        this.deadline = deadline;
        this.priority = priority;
    }

    public String getName() {
        return name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "タスク名: " + name + ", 期限: " + deadline + ", 優先度: " + priority + ", 状態: " + status;
    }
}

Java入門

class JSample1_1{
  public static void main(String args[]){

    int sum;

    sum = 0;
    for (int i = 1; i <= 100; i++){
      sum += i;
    }

    System.out.println(“sum = ” + sum);

    sum = 0;
    for (int i = 1; i <= 100; i++){
      sum += i;

      if (sum > 100){
        break;
      }
    }

    System.out.println(“sum = ” + sum);

  }
}

class JSample1_1{
  public static void main(String args[]){

    int sum;

    sum = 0;
    for (int i = 1; i <= 100; i++){
      sum += i;
    }

    System.out.println(“sum = ” + sum);

    sum = 0;
    for (int i = 1; i <= 100; i++){
      sum += i;

      if (sum > 100){
        break;
      }
    }

    System.out.println(“sum = ” + sum);

  }
}
class JSample1_1{
  public static void main(String args[]){

    int sum;

    sum = 0;
    for (int i = 1; i <= 100; i++){
      sum += i;
    }

    System.out.println(“sum = ” + sum);

    sum = 0;
    for (int i = 1; i <= 100; i++){
      sum += i;

      if (sum > 100){
        break;
      }
    }

    System.out.println(“sum = ” + sum);

  }
}
サンプルソース
//条件分岐の例
public class IfOne {
  public static void main(String args[]){
    //この下から順次実行されます。
    long t;//long型変数 t を宣言

    t=System.currentTimeMillis();//tに時刻をセット
    System.out.print(“ミリ秒の最後の一桁は、偶数?”);//改行せずに表示

    //一番したが、一桁なら「〇」を表示
    if (t%2==0){
      System.out.print(“〇”);
    }
  }

public class Compute {
public static void main(String args[]){
int a;//int型変数aを宣言
int b;//int型変数bを宣言
int add,sub,mlt,div,mdl,ave;//幾つのint型変数をまとめて宣言


a=8;//aに8をセット
b=3;//bに3をセット

add=a+b;//足し算を実施
sub=a-b;//引き算を実施
mlt=a*b;//掛け算を実施
div=a/b;//割り算を実施
mdl=a%b;//余りを計算
ave=(a+b)/2;//平均を計算

//結果の表示
System.out.print(“a+b=”);
System.out.println(add);

System.out.print(“a-b=”);
System.out.println(sub);

System.out.print(“a×b=”);
System.out.println(mlt);

System.out.print(“a÷b=”);
System.out.println(div);

System.out.print(“a%b=”);
System.out.println(mdl);

System.out.print(“平均=”);
System.out.println(ave);

}
}
public class Hellow {
public  static void main(String args[]){
//この下から、内容が順次実行されます
System.out.println(“Hellow Java”);//Hellow Javaと出力
System.out.println(“こんにちは”);//こんにちはと出力
System.out.println(“ニーハオ”);//ニーハオと出力
}
}

public class Sample10b{
public static void main(String[] args){

String[] nations ={
“スウェーデン”,”ドミニカ共和国”,”スロベニア”,”ベラルーシ”
};

String[] capitals ={
“ロンドン”,”マスカット”,”凹田”,”ストックホルム”,
“サンとドミンゴ”,”トビリシ”,”プノンペン”,”ホニアラ”,
“リュブリャナ”,”ファドゥーツ”,”アンタナナリボ”,”テグシガルパ”,
“キエフ”,”ミンスク”,”カイロ”,”パナマシティ”
};

int capitalIndex = 0;
for(int qID=1; qID<5; qID++){
System.out.println(“Q” + qID + “:”+ nations[qID-1]);
for(int i = 1; i<5; i++){
System.out.println(i + ” . ” + capitals[capitalIndex]);
capitalIndex++;
}
}
}
}
http://www.javadrive.jp/start/for/index6.html