Last active
July 3, 2023 00:22
-
-
Save LeoAndo/48973fbeec3b77ad7050640cbe4dcee2 to your computer and use it in GitHub Desktop.
掛け算表を作成するプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.InputMismatchException; | |
import java.util.NoSuchElementException; | |
import java.util.Scanner; | |
public class MultiplicationTable { | |
public static void main(String[] args) { | |
System.out.print("数値を入力してください: "); | |
try (final Scanner scan = new Scanner(System.in)) { // try with resource構文で scan.closeの呼び出し忘れを防ぐ. | |
final int tableSize = scan.nextInt(); | |
if (tableSize < 1 || 20 < tableSize) {// 条件に合わなければ、早期リターンする. | |
System.out.println("1から20までの整数を入力してください"); | |
return; | |
} | |
System.out.print(" |"); | |
final StringBuilder hyphen = new StringBuilder("----"); | |
for (int i = 1; i <= tableSize; i++) { | |
System.out.printf("%4d", i); // 最小桁数4桁で、0埋めしない %04d と書くと0埋めされる. | |
hyphen.append("----"); | |
} | |
System.out.printf("\n%s\n", hyphen); | |
for (int i = 1; i <= tableSize; i++) { | |
System.out.printf("%2d|", i); | |
for (int j = 1; j <= tableSize; j++) { | |
System.out.printf("%4d", i * j); | |
} | |
System.out.println(); | |
} | |
} catch (InputMismatchException ex) { | |
System.err.println("1から20までの整数を入力してください"); | |
} catch (IllegalStateException ex) { | |
System.err.println("スキャナがすでに閉じているため処理できません"); | |
} catch (NoSuchElementException ex) { | |
System.err.println(ex.getLocalizedMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
実行結果: 入力値20 (範囲内)
実行結果: 入力値0 (範囲外)