
Java基本構文と制御構造 課題集 (全30問)
初級問題 (9問) 基本構文とデータ型 中級問題 (15問) 制御構造 配列と制御構造 上級問題 (6問) 解答例 初級問題の解答 int age = 25; […]
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ゼロ除算が発生しました");
}
try {
int[] arr = new int[5];
arr[10] = 50; // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("配列範囲外アクセス");
} catch (Exception e) {
System.out.println("その他の例外");
}
FileReader reader = null;
try {
reader = new FileReader("file.txt");
// ファイル操作...
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
// 例外発生コード
} catch (Exception e) {
System.out.println("エラーメッセージ: " + e.getMessage());
e.printStackTrace();
}
try {
Files.readAllLines(Paths.get("nonexistent.txt"));
} catch (IOException e) {
System.out.println("ファイル読み込みエラー");
}
String str = null;
try {
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("null参照エラー");
}
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
try {
// 処理...
} catch (IOException e) {
System.out.println("エラー処理");
throw e;
}
try {
// 処理...
} catch (SQLException e) {
throw new MyException("データベースエラー", e);
}
try (FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try (FileWriter fw = new FileWriter("output.txt")) {
fw.write("Hello, World!\n");
fw.write("Javaファイル入出力\n");
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader br = new BufferedReader(new FileReader("largefile.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
File file = new File("test.txt");
if (file.exists()) {
System.out.println("ファイルが存在します");
} else {
System.out.println("ファイルが存在しません");
}
try (FileInputStream fis = new FileInputStream("image.jpg")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// バイナリデータ処理...
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello"のバイト表現
try (FileOutputStream fos = new FileOutputStream("binary.dat")) {
fos.write(data);
} catch (IOException e) {
e.printStackTrace();
}
try (InputStream is = new FileInputStream("source.txt");
OutputStream os = new FileOutputStream("destination.txt")) {
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
File dir = new File("new_directory");
if (dir.mkdir()) {
System.out.println("ディレクトリ作成成功");
} else {
System.out.println("ディレクトリ作成失敗");
}
File file = new File("temp.txt");
if (file.delete()) {
System.out.println("ファイル削除成功");
} else {
System.out.println("ファイル削除失敗");
}
File file = new File("document.txt");
System.out.println("サイズ: " + file.length() + " bytes");
System.out.println("最終更新: " + new Date(file.lastModified()));
try (BufferedReader br = Files.newBufferedReader(Paths.get("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
// 複数例外が発生する可能性のあるコード
} catch (IOException | SQLException e) {
System.out.println("IOまたはSQLエラー: " + e.getMessage());
}
try (InputStream is = new FileInputStream("file.txt")) {
throw new IOException("ブロック内例外");
} catch (Exception e) {
System.out.println("キャッチした例外: " + e.getMessage());
for (Throwable t : e.getSuppressed()) {
System.out.println("抑制された例外: " + t.getMessage());
}
}
Optional optional = Optional.ofNullable(getPossiblyNullString());
String result = optional.orElse("デフォルト値");
int value = 15;
assert value > 10 : "値が10以下です";
// VMオプションで-eaを指定する必要あり
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class Account {
private double balance;
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("残高不足: " + balance);
}
balance -= amount;
}
}
// 使用例
try {
Account account = new Account();
account.withdraw(1000);
} catch (InsufficientFundsException e) {
System.out.println("エラー: " + e.getMessage());
}
Path path = Paths.get("example.txt");
try {
// ファイル読み込み
List lines = Files.readAllLines(path);
// ファイル書き込み
Files.write(path, Arrays.asList("Line1", "Line2"),
StandardOpenOption.CREATE);
// ファイルコピー
Files.copy(path, Paths.get("copy.txt"),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
class Person implements Serializable {
private String name;
private int age;
// コンストラクタ、ゲッター等は省略
}
// シリアライズ
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("person.ser"))) {
oos.writeObject(new Person("Alice", 25));
}
// デシリアライズ
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("person.ser"))) {
Person p = (Person) ois.readObject();
System.out.println(p.getName());
}
import java.util.logging.*;
Logger logger = Logger.getLogger("MyLogger");
try {
// ファイルハンドラの設定
FileHandler fh = new FileHandler("app.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// 例外をログに記録
int result = 10 / 0;
} catch (Exception e) {
logger.log(Level.SEVERE, "例外が発生しました", e);
}
class FileTransaction {
public static void backupAndWrite(Path file, List lines) throws IOException {
Path backup = Paths.get(file.toString() + ".bak");
Files.copy(file, backup, StandardCopyOption.REPLACE_EXISTING);
try {
Files.write(file, lines, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
// 失敗したらバックアップから復元
Files.copy(backup, file, StandardCopyOption.REPLACE_EXISTING);
throw e;
}
}
}
class ResourceManager {
public static void withFileReader(String filename, Consumer action) {
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
action.accept(br);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static void withFileWriter(String filename, Consumer action) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
action.accept(bw);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
// 使用例
ResourceManager.withFileReader("input.txt", reader -> {
// リーダーを使用した処理
});