- public class Print01 {
- public static void main(String[] args) {
- System.out.println("Hello World!");
- System.out.println("みなさん、こんにちは。");
- }
- }
□ 実行結果
$ java Print01 Hello World! みなさん、こんにちは。□"Print02.java"
- public class Print02 {
- public static void main(String[] args) {
- System.out.print("Hello World!");
- System.out.print("みなさん、こんにちは。");
- }
- }
□ 実行結果
$ java Print02 Hello World!みなさん、こんにちは。
- public class Print03 {
- public static void main(String[] args) {
- System.out.print("コマンドライン引数の値 = ");
- System.out.println(args[0]);
- }
- }
□ 実行結果
$ java Print03 コマンドライン引数の値 = Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Print03.main(Print03.java:4) $ java Print03 Hello コマンドライン引数の値 = Hello
- public class Print04 {
- public static void main(String[] args) {
- System.out.print("コマンドライン引数の値 = ");
- System.out.println(Double.parseDouble(args[0]));
- }
- }
□ 実行結果
$ java Print04 Hello コマンドライン引数の値 = Exception in thread "main" java.lang.NumberFormatException: For input string: "Hello" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224) at java.lang.Double.parseDouble(Double.java:482) at Print04.main(Print04.java:4) $ java Print04 3.14 コマンドライン引数の値 = 3.14 $ java Print04 -10 コマンドライン引数の値 = -10.0
■ 基本データ型
- public class Variable50 {
- public static void main(String[] args) {
- byte b = 10;
- short s = -200;
- int i = 3000;
- long l = -40000;
- float f = 5.6f;
- double d = -78.901e23;
- char c = 'a';
- boolean bo = true;
- System.out.println("byte : " + b);
- System.out.println("short : " + s);
- System.out.println("int : " + i);
- System.out.println("long : " + l);
- System.out.println("float : " + f);
- System.out.println("double : " + d);
- System.out.println("char : " + c);
- System.out.println("boolean : " + bo);
- }
- }
□ 実行結果
$java Variable50 byte : 10 short : -200 int : 3000 long : -40000 float : 5.6 double : -7.8901E24 char : a boolean : true
- public class Bmi01 {
- public static void main(String[] args) {
- double weight = Double.parseDouble(args[0]);
- double hight = Double.parseDouble(args[1]);
- //
- // ここにコードを記述してください。
- //
- }
- }
□ 実行結果
$ java Bmi01 60 1.7 BMI = 20.761245674740486
- public class Bmi02 {
- public static void main(String[] args) {
- int weight = Integer.parseInt(args[0]);
- int hight = Integer.parseInt(args[1]);
- //
- // ここにコードを記述してください。
- //
- }
- }
□ 実行結果
$ java Bmi02 60 170 BMI = 20
- public class Area01 {
- public static void main(String[] args) {
- double a = Double.parseDouble(args[0]);
- double b = Double.parseDouble(args[1]);
- //
- // ここにコードを記述してください。
- //
- }
- }
□ 実行結果
$ java Area01 10 20 円の面積 = 314.0 三角形の面積 = 100.0 四角形の面積 = 200.0 $ java Area01 1.1 2.2 円の面積 = 3.7994000000000008 三角形の面積 = 1.2100000000000002 四角形の面積 = 2.4200000000000004
- public class Area02 {
- public static void main(String[] args) {
- double a = Double.parseDouble(args[0]);
- double b = Double.parseDouble(args[1]);
- //
- // ここにコードを記述してください。
- //
- }
- }
□ 実行結果
$ java Area01 1.1 2.2 円の面積 = 4 三角形の面積 = 1 四角形の面積 = 2
- public class Length01 {
- public static void main(String[] args) {
- double a = Double.parseDouble(args[0]);
- double b = Double.parseDouble(args[1]);
- //
- // ここにコードを記述してください。
- //
- }
- }
□ 実行結果
$ java Length01 1 1 円周の長さ = 6.283185307179586 三角形の周の長さ = 3.23606797749979 四角形の周の長さ = 4.0
- public class EvenOdd01 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- System.out.println( /* ここにコードを記述してください */);
- }
- }
□ 実行結果
$ java EvenOdd01 4 true $ java OddEven01 5 false
- public class LeapYear21 {
- public static void main(String[] args) {
- int year = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java LeapYear21 2004 true
- public class Range21 {
- public static void main(String[] args) {
- int a = Integer.parseInt(args[0]);
- int b = Integer.parseInt(args[1]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Range21 10 20 true
- public class Triangle21 {
- public static void main(String[] args) {
- int a = Integer.parseInt(args[0]);
- int b = Integer.parseInt(args[1]);
- int c = Integer.parseInt(args[2]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Triangle21 2 3 4 true
- public class CodePrint01 {
- public static void main(String[] args) {
- char c = 'a';
- System.out.println(???? + "'s code is " + ????);
- }
- }
□ 実行結果
a's code is 97
- public class CodePrint02 {
- public static void main(String[] args) {
- char c = ????????????? ;
- System.out.println("'" + c + "': " + ???????????????????? );
- }
- }
□ 実行結果
$ java CodePrint02 a 'a': 61
- public class NegativeNumber {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- int nn = ????;
- System.out.print("Decimal: ");
- System.out.println("-(" + n + ") = " + nn);
- System.out.print("HexDecimal: ");
- System.out.println("-(" + Integer.toHexString(n) + ") = " + Integer.toHexString(nn));
- }
- }
□ 実行結果
$ java NegativeNumber 1234 Decimal: -(1234) = -1234 HexDecimal: -(4d2) = fffffb2e
- public class Encoding01 {
- public static void main(String[] args) {
- int a = args[0].charAt(0);
- int key = 0x3;
- int b = ?????? ;
- System.out.println((char)a + "(" + Integer.toBinaryString(a)
- + ") encode to: "
- + (char)b + "(" + Integer.toBinaryString(b) + ")");
- }
- }
□ 実行結果
$ java Encoding01 a a(1100001) encode to: b(1100010)
■ if 文
- public class Min01 {
- public static void main(String[] args) {
- int a = Integer.parseInt(args[0]);
- int b = Integer.parseInt(args[1]);
- int c = Integer.parseInt(args[2]);
- int min = a;
- // ここにコードを記述してください。
- System.out.println(a + ", " + b + ", " + c + " の最小値は " + min);
- }
- }
□ 実行結果
$ java Min01 1 2 3 1, 2, 3 の最小値は 1
- public class MinMax {
- public static void main(String[] args) {
- int a = Integer.parseInt(args[0]);
- int b = Integer.parseInt(args[1]);
- int c = Integer.parseInt(args[2]);
- int min = a;
- int max = a;
- // ここにコードを記述してください。
- System.out.println(a + ", " + b + ", " + c + " の最小値は " + min);
- System.out.println(a + ", " + b + ", " + c + " の最大値は " + max);
- }
- }
□ 実行結果
$ java MinMax 1 2 3 1, 2, 3 の最小値は 1 1, 2, 3 の最大値は 3
- public class Exchange02 {
- public static void main(String[] args) {
- int a = Integer.parseInt(args[0]); // コマンドラインからの引数をint型に変換します。
- int b = Integer.parseInt(args[1]); // コマンドラインからの引数をint型に変換します。
- // ここにコードを記述してください。
- System.out.println("小さい順に表示: " + a + ", " + b);
- }
- }
□ 実行結果
$ java Exchange02 2 5 小さい順に表示: 2, 5 $ java Exchange02 2 -5 小さい順に表示: -5, 2
- public class EvenOdd02 {
- public static void main(String[] args) {
- int a = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java EvenOdd02 10 10は偶数です。 $ java EvenOdd02 11 11は奇数です。
- public class Range11 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Range11 50 50は範囲内です $ java Range11 -1 -1は範囲外です $ java Range11 101 101は範囲外です
- public class Range12 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Range12 50 少し、がんばりましょう。 $ java Range12 -1 -1は範囲外です
- public class Bmi03 {
- public static void main(String[] args) {
- double weight = Double.parseDouble(args[0]);
- double hight = Double.parseDouble(args[1]);
- //
- // ここにコードを記述してください。
- //
- }
- }
□ 実行結果
$ java Bmi03 60 1.7 BMI = 20.761245674740486 判定は 標準
- public class Days00 {
- public static void main(String[] args) {
- int month = Integer.parseInt(args[0]);
- int days;
- // ここにコードを記述してください。
- System.out.println(month + " 月は " + days + " 日です。");
- }
- }
□ 実行結果
$ java Days00 2 2 月は 28 日です。
- public class Janken10 {
- public static void main(String[] args) {
- int user = Integer.parseInt(args[0]); // コマンドラインからの引数をint型に変換します。
- int computer = (int)(Math.random() * 3); // コンピューターの手
- // ここにコードを記述してください。
- System.out.print("あなた: " + user + ", コンピューター: " + computer);
- }
- }
□ 実行結果
$ java Janken10 0 あなた: 0, コンピューター: 1 あなたの勝ちです。
- public class LeapYear01 {
- public static void main(String[] args) {
- int year = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java LeapYear01 2004 2004年はうるう年です。
■ switch 文
- public class Match01 {
- public static void main(String[] args) {
- int a0 = 3;
- int a1 = 5;
- int a2 = 8;
- int n0 = Integer.parseInt(args[0]);
- int n1 = Integer.parseInt(args[1]);
- int n2 = Integer.parseInt(args[2]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Match01 8 4 6 やっと合いましたね。
- public class Match02 {
- public static void main(String[] args) {
- // ここにコードを記述してください。
- int a0 = 3;
- int a1 = 5;
- int a2 = 8;
- int n0 = Integer.parseInt(args[0]);
- int n1 = Integer.parseInt(args[1]);
- int n2 = Integer.parseInt(args[2]);
- // ここにコードを記述してください。
- }
- }
$ java Match02 引数は3個指定してください。 $ java Match02 1 2 34 34 は範囲外です。 $ java Match02 1 2 2 同じ数が指定されています。
■ for 文
- public class StarPrint01 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- System.out.println();
- }
- }
□ 実行結果
$ java StarPrint01 4 ****
- public class Kuku01 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- System.out.println();
- }
- }
□ 実行結果
$ java Kuku01 4 4 8 12 16 20 24 28 32 36
- public class Sum01 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- int s = 0;
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Sum01 1000 合計 = 1035, 最後に加算した数 = 45
- public class Progression01 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- System.out.println();
- }
- }
□ 実行結果
$ java Progression01 1000 1 2 4 8 16 32 64 128 256 512
□ 実行結果
$ java StarPrint02 4 **** **** **** ****
□ 実行結果
$ java StarPrint03 4 * ** *** ****
□ 実行結果
$ java StarPrint04 4 **** *** ** *
- public class Kuku02 {
- public static void main(String[] args) {
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Kuku02 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81
- public class Power01 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- double s = 1;
- // ここにコードを記述してください。
- System.out.println("s = " + s);
- }
- }
□ 実行結果
$ java Power01 10 s = 1024.0 $ java Power01 100 s = 1.2676506002282294E30
- public class All9 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- long r = 1;
- // ここにコードを記述してください。
- System.out.println(r + " * " + r + " = " + r * r);
- }
- }
□ 実行結果
$ java All9 2 99 * 99 = 9801
- public class All1 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- long r = 1;
- // ここにコードを記述してください。
- System.out.println(r + " * " + r + " = " + r * r);
- }
- }
□ 実行結果
$ java All1 4 1111 * 1111 = 1234321
- public class IsPrimeNumber {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java IsPrimeNumber 7 <-- 素数の場合、 <-- 何も出力されない。 $ java IsPrimeNumber 8 <-- 素数でない場合、 8 is not a prime number. <-- メッセージが出力される。
- public class CodePrint03 {
- public static void main(String[] args) {
- // ここにコードを記述してください。
- for ( /* ここにコードを記述してください。*/ ) {
- System.out.println("'" + (char)i + "': " + Integer.toHexString(i));
- }
- }
- }
□ 実行結果
$ java CodePrint03 あ お 'あ': 3042 'ぃ': 3043 'い': 3044 'ぅ': 3045 'う': 3046 'ぇ': 3047 'え': 3048 'ぉ': 3049 'お': 304a
- public class Encoding02 {
- public static void main(String[] args) {
- int a0 = args[0].charAt(0);
- int a1 = args[1].charAt(0);
- int key = 0x3;
- // ここにコードを記述してください。
- System.out.println((char)i + "(" + Integer.toBinaryString(i)
- + ") encode to: "
- + (char)b + "(" + Integer.toBinaryString(b) + ")");
- }
- }
- }
□ 実行結果
$ java Encoding02 0 9 0(110000) encode to: 3(110011) 1(110001) encode to: 2(110010) 2(110010) encode to: 1(110001) 3(110011) encode to: 0(110000) 4(110100) encode to: 7(110111) 5(110101) encode to: 6(110110) 6(110110) encode to: 5(110101) 7(110111) encode to: 4(110100) 8(111000) encode to: ;(111011) 9(111001) encode to: :(111010)
- public class MonteCarlo {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- double x, y;
- double pi;
- int c = 0;
- // ここにコードを記述してください。
- pi = 4d * c / n;
- System.out.println("pi = " + pi);
- }
- }
$ java MonteCarlo 1000 pi = 3.184 $ java MonteCarlo 10000 pi = 3.1308
□ 実行結果
$ java StarPrint05 4 **** *** ** *
□ 実行結果
$ java StarPrint06 4 * ** *** ****
□ 実行結果
$ java StarPrint07 4 ** **** ****** ******** ****** **** **
□ 実行結果
$ java Kuku03 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81
- public class For12 {
- public static void main(String[] args) {
- int s = Integer.parseInt(args[0]);
- for (// ここにコードを記述してください。) {
- for (// ここにコードを記述してください。) {
- System.out.print(j + " ");
- }
- System.out.println();
- }
- }
- }
□ 実行結果
$ java For12 18 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 : (中略) 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
- public class For121 {
- public static void main(String[] args) {
- int s = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java For121 18 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 : (中略) 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
■ while 文
- public class GCD01 {
- public static void main(String[] args) {
- int a = Integer.parseInt(args[0]);
- int b = Integer.parseInt(args[1]);
- int r;
- while ( /* ここにコードを記述してください。*/ ) {
- // ここにコードを記述してください。
- }
- System.out.println(args[0] + " と " + args[1] + " の最大公約数は, " + b + " です。" );
- }
- }
□ 実行結果
$ java GCD01 12 32 12 と 32 の最大公約数は, 4 です。
- public class Fibonacci01 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- int f = 1;
- int g = 1;
- int h = 0;
- System.out.print(f + " " + g + " ");
- // ここにコードを記述してください。
- System.out.println();
- }
- }
□ 実行結果
$ java Fibonacci01 1000 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
□ 実行結果
$ java Kuku04 30 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 5 10 15 20 25 30 6 12 18 24 30 7 14 21 28 8 16 24 9 18 27
□ 実行結果
$ java Kuku05 30 (空白行が出ます) 32 36 30 35 40 45 30 36 42 48 54 35 42 49 56 63 32 40 48 56 64 72 36 45 54 63 72 81
- public class Search01 {
- public static void main(String[] args) {
- char c = args[1].charAt(0); // コマンドラインの第2引数の1文字目を取得
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Search01 "Hello World" l 'l' は 'Hello World' の 3 番目の文字です。
- public class Search02 {
- public static void main(String[] args) {
- char c = args[1].charAt(0); // コマンドラインの第2引数の1文字目を取得
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Search02 "Hello World" l 'l' は 'Hello World' の 3 番目の文字です。 'l' は 'Hello World' の 4 番目の文字です。 'l' は 'Hello World' の 10 番目の文字です。
- public class Search03 {
- public static void main(String[] args) {
- char c = args[1].charAt(0); // コマンドラインの第2引数の1文字目を取得
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Search03 "Hello World" l 2 'l' は 'Hello World' の 4 番目の文字です。
- public class Days10 {
- public static void main(String[] args) {
- int month = Integer.parseInt(args[0]); // コマンドラインからの引数をint型に変換します。
- // 月 1 2 3 4 5 6 7 8 9 10 11 12
- int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 日数
- // 索引 0 1 2 3 4 5 6 7 8 9 10 11
- System.out.println(month + " 月は " + days[month - 1] + " 日です。");
- }
- }
□ 実行結果
$ java Days10 2 2 月は 28 日です。
- public class Array71 {
- public static void main(String[] args) {
- int[] a = new int[4];
- a[0] = 100;
- a[1] = -100;
- a[2] = 0;
- a[3] = 0xffff;
- System.out.println(ArrayUtil.toString(a));
- }
- }
□ 実行結果
$java Array71 [100, -100, 0, 65535]
- public class Array72 {
- public static void main(String[] args) {
- int[] a = {100, -100, 0, 0xffff};
- System.out.println(ArrayUtil.toString(a));
- }
- }
□ 実行結果
$java Array72 [100, -100, 0, 65535]
- public class Sum11 {
- public static void main(String[] args) {
- int[] a = {100, -100, 0, 0xff, -077};
- // ここにコードを記述してください。
- System.out.println("a[] = " + ArrayUtil.toString(a));
- System.out.println("sum = " + sum);
- }
- }
□ 実行結果
$ java Sum11 a[] = [100, -100, 0, 255, -63] sum = 192
- public class MinMax11 {
- public static void main(String[] args) {
- int[] a = {100, -100, 0, 0xff, -077};
- // ここにコードを記述してください。
- System.out.println("a[] = " + ArrayUtil.toString(a));
- System.out.println("min = " + min + ", max = " + max);
- }
- }
□ 実行結果
$ java MinMax11 a[] = [100, -100, 0, 255, -63] min = -100, max = 255
- public class MinMax12 {
- public static void main(String[] args) {
- int[] a = new int[0];
- // ここにコードを記述してください。
- System.out.println("a[] = " + ArrayUtil.toString(a));
- System.out.println("min = " + min + ", max = " + max);
- }
- }
□ 実行結果
$ java MinMax12 a[] = [] min = 2147483647, max = -2147483648 a[] = [100] min = 100, max = 100 a[] = [100, -100, 0, 255, -63] min = -100, max = 255
- public class Array53 {
- public static void main(String[] args) {
- int[] a = new int[10];
- for (int i = 0; i < a.length; i++) {
- a[i] = i; // 配列要素に値を設定
- }
- System.out.println(ArrayUtil.toString(a));
- }
- }
□ 実行結果
$java Array53 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- public class ArgsPrint01 {
- public static void main(String[] args) {
- System.out.println("args.length = " + args.length);
- for (int i = 0; i < args.length; i++) {
- System.out.println(i + " : " + args[i]);
- }
- }
- }
□ 実行結果
$ java ArgsPrint01 args.length = 0 $ java ArgsPrint01 Hello Java World args.length = 3 0 : Hello 1 : Java 2 : World $ java ArgsPrint01 "Hello Java World" args.length = 1 0 : Hello Java World
- public class Array31 {
- public static void main(String[] args) {
- int[] a = new int[10];
- for (int i = 0; i < a.length; i++) {
- a[i] = i;
- }
- System.out.println("a[] = " + ArrayUtil.toString(a));
- System.out.println();
- // 要素の正順に配列bにコピーする。
- int[] b = new int[a.length];
- // コードを記述してください。
- // 要素の逆順に配列cにコピーする。
- int[] c = new int[a.length];
- // コードを記述してください。
- // 要素を逆にする。
- int w;
- // コードを記述してください。
- // 要素を2つずらす。このとき、要素数が2つの配列は作業用として使用してもよい。
- int[] t = new int[2];
- // コードを記述してください。
- // a, b, cのプリント
- System.out.println("** a, b, cのプリント **");
- System.out.println("a[] = " + ArrayUtil.toString(a));
- System.out.println("b[] = " + ArrayUtil.toString(b));
- System.out.println("c[] = " + ArrayUtil.toString(c));
- System.out.println();
- // さらに要素を2つずらす。このとき、作業用の変数をひとつ使用してもよい。
- int u;
- // コードを記述してください。
- System.out.println("** 要素ずれのプリント **");
- System.out.println("a[] = " + ArrayUtil.toString(a));
- }
- }
□ 実行結果
$java Array31 a[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ** a, b, cのプリント ** a[] = [7, 6, 5, 4, 3, 2, 1, 0, 9, 8] b[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] c[] = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ** 要素ずれのプリント ** a[] = [5, 4, 3, 2, 1, 0, 9, 8, 7, 6]
- public class SequentialSearch {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- int[] a = {50, 30, 40, 10, 20};
- int i = search(a, n);
- if (i >= 0) {
- System.out.println(n + " was found.(index = " + i + ")");
- } else {
- System.out.println(n + " was not found.");
- }
- }
- public static int search(int[] a, int n) {
- for (int i = 0; i < a.length; i++) {
- //
- // ここにコードを記述してください。
- //
- }
- return -1;
- }
- }
□ 実行結果
$java SequentialSearch 50 50 was found.(index = 0) $java SequentialSearch 51 51 was not found.
- public class BinarySearch {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- int[] a = {10, 20, 30, 40, 50};
- int i = search(a, n);
- if (i >= 0) {
- System.out.println(n + " was found.(index = " + i + ")");
- } else {
- System.out.println(n + " was not found.");
- }
- }
- public static int search(int[] a, int n) {
- int l = 0;
- int h = a.length - 1;
- int m;
- while (/* ここにコードを記述してください。*/) {
- m = (l + h) / 2;
- if (a[m] < n) {
- l = m + 1;
- } else if (a[m] > n) {
- h = m - 1;
- } else {
- return m;
- }
- }
- return -1;
- }
- }
□ 実行結果
$java BinarySearch 50 50 was found.(index = 4) $java BinarySearch 51 51 was not found.
- public class Rank01 {
- public static void main(String[] args) {
- int[] a = {5, 3, 6, 5, 8, 6, 9, 1, 3, 3};
- int[] rank = new int[a.length];
- for (int i = 0; i < a.length; i++) {
- rank[i] = 1;
- for (int j = 0; j < a.length; j++) {
- //
- // ここにコードを記述してください。
- //
- }
- }
- for (int i = 0; i < a.length; i++) {
- System.out.println(a[i] + " - " + rank[i]);
- }
- }
- }
□ 実行結果
$java Rank01 5 - 5 3 - 7 6 - 3 5 - 5 8 - 2 6 - 3 9 - 1 1 - 10 3 - 7 3 - 7
- public class Count01 {
- public static void main(String[] args) {
- int[] a = {2, 2, 3, 5, 5, 5, 7, 8, 8};
- int prevValue = a[0];
- int count = 0;
- for (int i = 0; i < a.length; i++) {
- if (prevValue == a[i]) {
- //
- // ここにコードを記述してください。
- //
- } else {
- System.out.println(prevValue + " : " + count);
- //
- // ここにコードを記述してください。
- //
- }
- }
- System.out.println(prevValue + " : " + count);
- }
- }
□ 実行結果
$java Count01 2 : 2 3 : 1 5 : 3 7 : 1 8 : 2
- public class Matching01 {
- public static void main(String[] args) {
- int[] a = {10, 20, 30, 40, 50, Integer.MAX_VALUE};
- int[] b = {15, 20, 30, 35, 50, 60, Integer.MAX_VALUE};
- System.out.println(ArrayUtil.toString(match(a, b)));
- }
- public static int[] match(int[] a, int[] b) {
- int[] c = new int[a.length + b.length];
- int i = 0, j = 0, k = 0;
- while (a[i] < Integer.MAX_VALUE || b[j] < Integer.MAX_VALUE) {
- if (a[i] < b[j]) {
- //
- // ここにコードを記述してください。
- //
- } else if (a[i] == b[j]) {
- //
- // ここにコードを記述してください。
- //
- } else {
- //
- // ここにコードを記述してください。
- //
- }
- }
- c[k] = Integer.MAX_VALUE;
- return c;
- }
- }
□ 実行結果
$java Matching01 [10, 15, 20, 30, 35, 40, 50, 60, 2147483647, 0, 0, 0, 0]
- public class Sort01 {
- public static void main(String[] args) {
- int n = args.length;
- int[] a = new int[n];
- for (int i = 0; i < n; i++) {
- a[i] = Integer.parseInt(args[i]);
- }
- for (int i = 0; i < n - 1; i++) {
- for (int j = i + 1; j < n; j++) {
- //
- // ここにコードを記述してください。
- //
- }
- }
- System.out.println(ArrayUtil.toString(a));
- }
- }
□ 実行結果
$java Sort01 6 3 5 1 [1, 3, 5, 6]
- // 0703
- public class ArrayUtil {
- // 途中省略
- // 乱数設定
- public static int[] getRandomElement(int[] a) {
- // コードを記述してください。
- return a;
- }
- }
- public class Array73 {
- public static void main(String[] args) {
- int[] a = new int[Integer.parseInt(args[0])];
- System.out.println(ArrayUtil.toString(ArrayUtil.getRandomElement(a)));
- }
- }
□ 実行結果
$java Array73 10 [3, 3, 0, 7, 5, 8, 9, 5, 7, 4]
- public class Kuku11 {
- public static void main(String[] args) {
- int[][] a = new int[9][9];
- // コードを記述してください。
- }
- }
□ 実行結果
$java Kuku11 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81
- public class Kuku12 {
- public static void main(String[] args) {
- int[][] a = new int[9][9];
- // コードを記述してください。
- }
- }
□ 実行結果
$java Kuku12 [1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 4, 6, 8, 10, 12, 14, 16, 18] [3, 6, 9, 12, 15, 18, 21, 24, 27] [4, 8, 12, 16, 20, 24, 28, 32, 36] [5, 10, 15, 20, 25, 30, 35, 40, 45] [6, 12, 18, 24, 30, 36, 42, 48, 54] [7, 14, 21, 28, 35, 42, 49, 56, 63] [8, 16, 24, 32, 40, 48, 56, 64, 72] [9, 18, 27, 36, 45, 54, 63, 72, 81]
- public class Janken11 {
- public static void main(String[] args) {
- int user = Integer.parseInt(args[0]); // コマンドラインからの引数をint型に変換します。
- int computer = (int)(Math.random() * 3); // コンピューターの手
- String[] te = {"ぐー", "ちょき", "ぱー"};
- char[][] kekka = {{'分', '勝', '負'} // ぐー
- , {'負', '分', '勝'} // ちょき
- , {'勝', '負', '分'}}; // ぱー
- //コンピューター ぐー ちょき ぱー
- System.out.print("あなた: " + te[user] + ", コンピューター: " + te[computer]);
- System.out.println(" --> 結果: " + kekka[user][computer]);
- }
- }
□ 実行結果
$ java Janken11 0 あなた: ぐー, コンピューター: ちょき --> 結果: 勝
- public class Janken12 {
- public static void main(String[] args) {
- String[] te = {"ぐー", "ちょき", "ぱー"};
- char[][] kekka = {{'分', '勝', '負'} // ぐー
- , {'負', '分', '勝'} // ちょき
- , {'勝', '負', '分'}}; // ぱー
- //コンピューター ぐー ちょき ぱー
- int win = 0;
- int lose = 0;
- int draw = 0;
- for (int i = 0; i < args.length; i++) {
- // ここにコードを記述してください。
- }
- System.out.println(win + " 勝 " + lose + " 負 " + draw + " 分 ");
- }
- }
□ 実行結果
$ java Janken12 0 1 2 0 1 2 あなた: ぐー, コンピューター: ぐー --> 結果: 分 あなた: ちょき, コンピューター: ぱー --> 結果: 勝 あなた: ぱー, コンピューター: ぱー --> 結果: 分 あなた: ぐー, コンピューター: ちょき --> 結果: 勝 あなた: ちょき, コンピューター: ぐー --> 結果: 負 あなた: ぱー, コンピューター: ぐー --> 結果: 勝 3 勝 1 負 2 分
- public class Match03 {
- public static void main(String[] args) {
- int[] a = {(int)(Math.random() * 10), (int)(Math.random() * 10), (int)(Math.random() * 10)};
- int[] n = {Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2])};
- int s = 0;
- System.out.println("コンピューターの数字 = " + ArrayUtil.toString(ArrayUtil.sort(a)));
- System.out.println(" あなたの数字 = " + ArrayUtil.toString(ArrayUtil.sort(n)));
- // ここにコードを記述してください。
- switch (s) {
- case 0:
- System.out.println("まったく違います。");
- break;
- case 1:
- System.out.println("やっと合いましたね。");
- break;
- case 2:
- System.out.println("もう少しです。");
- break;
- default:
- System.out.println("おめでとうございます。");
- break;
- }
- }
- }
□ 実行結果
$ java Match03 2 4 4 コンピューターの数字 = [4, 5, 7] あなたの数字 = [2, 4, 4] やっと合いましたね。 $ java Match03 2 4 4 コンピューターの数字 = [1, 1, 7] あなたの数字 = [2, 4, 4] まったく違います。
- public class Igo01 {
- public static void main(String[] args) {
- int n = 19;
- char[][] ban = new char[n][n];
- char[] ishi = {'\u3000'/*日本語の空白文字*/, '●', '○'};
- // コードを記述してください。
- ArrayUtil.printArray(ban);
- }
- }
- // 0712
- public class ArrayUtil {
- :
- static void printArray(char[][] a) {
- // コードを記述してください。
- }
- }
□ 実行結果
$java Igo01 ● ◯ ● ◯ ● ● ◯ ● ● ● ● ● ◯ ● ◯ ◯ ● ◯ ● ◯ ● ● ● ◯ ● ● ◯ ● ● ◯ ◯ ◯ ◯ ◯ ◯ ◯ ● ◯ ◯ ◯ ● ◯ ● ◯ ◯ ◯ ◯ ◯ ◯ ● ◯ ● ◯ ◯ ● ● ◯ ● ◯ ◯ ● ● ● ● ◯ ● ◯ ◯ ● ● ● ◯ ◯ ◯ ● ◯ ● ◯ ● ● ◯ ◯ ● ◯ ◯ ● ● ◯ ◯ ◯ ◯ ◯ ● ● ● ◯ ● ◯ ● ● ● ◯ ● ● ● ● ◯ ◯ ● ◯ ● ◯ ◯ ● ◯ ◯ ◯ ◯ ● ◯ ◯ ◯ ● ● ● ● ◯ ● ● ◯ ◯ ● ◯ ◯ ● ● ● ● ◯ ◯ ◯ ● ● ● ◯ ● ◯ ● ◯ ● ◯ ● ◯ ◯ ● ◯ ◯ ◯ ◯ ● ● ◯ ● ◯ ● ● ◯ ◯ ● ● ● ● ● ● ● ◯ ◯ ● ● ◯ ◯ ◯ ● ◯ ● ◯ ● ◯ ◯ ◯ ◯ ◯ ◯ ◯ ● ● ◯ ● ● ● ● ◯ ● ● ◯ ◯ ◯ ● ◯ ◯ ● ● ● ◯ ◯ ● ● ◯ ● ● ● ◯ ● ◯ ◯ ● ● ● ● ◯ ● ●
- public class Encoding03 {
- public static void main(String[] args) {
- char[] a = args[0].toCharArray();
- int key = 0x3;
- // ここにコードを記述してください。
- System.out.println("'" + args[0] + "' encode to: '" + e + "'");
- }
- }
□ 実行結果
$ java Encoding03 "Hello World" 'Hello World' encode to: 'Kfool#Tlqog'
- public class ReversePolishNotation {
- int[] stack = new int[2];
- int sp;
- public int calc(String str) {
- int d1, d2;
- String s;
- sp = 0;
- for (int i = 0; i < str.length(); i++) {
- switch (str.charAt(i)) {
- case '+':
- d1 = pop();
- d2 = pop();
- push(d2 + d1);
- break;
- // ここにコードを記述してください。
- default:
- push(Integer.parseInt(str.substring(i, i+1)));
- }
- }
- return pop();
- }
- private void push(int d) {
- stack[sp++] = d;
- }
- private int pop() {
- return stack[--sp];
- }
- public static void main(String[] args) {
- System.out.println("計算式 = " + args[0]);
- ReversePolishNotation rpn = new ReversePolishNotation();
- System.out.println("結果 = " + rpn.calc(args[0]));
- }
- }
□ 実行結果
$ java ReversePolishNotation 98+7%6*5/4- 計算式 = 98+7%6*5/4- <-- この式は、((((9+8)%7)*6)/5)-4 を意味します。 結果 = -1
- public class Eratosthenes {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- boolean[] prime = new boolean[n];
- for (int i = 0; i < n; i++) {
- prime[i] = true;
- }
- // ここにコードを記述してください。
- for (int i = 2; i < n; i++) {
- if (prime[i]) {
- System.out.print(" " + i);
- }
- }
- System.out.println();
- }
- }
□ 実行結果
$ java Eratosthenes 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
- public class CheckDigit01 {
- final static int[] weight = {19, 17, 13, 11, 7, 1};
- final static int n = weight.length;
- public static void main(String[] args) {
- int[] digit = new int[n];
- int len = args[0].length();
- if (len != n - 1 && len != n) {
- System.out.println("5桁または6桁の数字を指定してください。");
- System.exit(1);
- }
- for (int i = 0; i < Math.min(n, len); i++) {
- digit[i] = Integer.parseInt(args[0].substring(i, i+1));
- }
- if (len == n - 1) {
- System.out.println("チェック・ディジットつきの数は "
- + setCheckDigit(digit) + " です。");
- } else if (isValidDigit(digit)) {
- System.out.println(args[0] + "は正しい数です。");
- } else {
- System.out.println(args[0] + "は正しくありません。");
- }
- }
- public static String setCheckDigit(int[] d) {
- // ここにコードを記述してください。
- return sb.toString();
- }
- public static boolean isValidDigit(int[] d) {
- // ここにコードを記述してください。
- return((s % 10) == 0);
- }
- }
□ 実行結果
$ java CheckDigit01 01234 チェック・ディジットつきの数は 012346 です。 $ java CheckDigit01 012346 012346は正しい数です。 $ java CheckDigit01 012345 012345は正しくありません。
■ クラスの定義
- public class Book {
- // ここにコードを記述してください。
- }
□ Book.javaクラスをテストするアプリケーションBookTest.java
- public class BookTest {
- public static void main(String[] args) {
- Book b1 = new Book();
- b1.title =args[0];
- b1.author = args[1];
- System.out.println(" Title:" + b1.title);
- System.out.println("Author:" + b1.author);
- }
- }
□ 実行結果
$ java BookTest JavaBook Maruno Title:JavaBook Author:Maruno
- public class ArgsUtil {
- public static boolean isValid(int count, String[] args, String message) {
- //
- // ここにコードを記述してください。
- //
- }
- }
- public class ArgsTest {
- public static void main(String[] args) {
- if (!ArgsUtil.isValid(1, args, "引数をひとつ指定してください。")) {
- System.exit(1); // アプリケーションを終了します
- }
- System.out.println("引数: " + args[0]);
- }
- }
□ 実行結果
$ java ArgsTest 引数をひとつ指定してください。 $ java ArgsTest Hello 引数: Hello $ java ArgsTest Hello World 引数をひとつ指定してください。 $ java ArgsTest "Hello World" 引数: Hello World
- public class Graph {
- public static String getStars(int n) {
- //
- // ここにコードを記述してください。
- //
- }
- }
- public class TestGraph {
- public static void main(String[] args) {
- System.out.println(Graph.toStarString(Integer.parseInt(args[0])));
- }
- }
□ 実行結果
$ java TestGraph 5 *****
- public class GCD {
- public static int getGCD(int a, int b) {
- int r;
- while ((r = a % b) != 0) {
- a = b;
- b = r;
- }
- // ここにコードを記述してください。
- }
- }
- public class TestGCD {
- public static void main(String[] args) {
- System.out.println(args[0] + " と " + args[1] + " の最大公約数は, " +
- GCD.getGCD(Integer.parseInt(args[0]), Integer.parseInt(args[1])) + " です。" );
- }
- }
□ 実行結果
$ java TestGCD 12 32 12 と 32 の最大公約数は, 4 です。
- public class PrimeNumber {
- public static boolean isPrimeNumber(int n) {
- //
- // ここにコードを記述してください。
- //
- return true;
- }
- }
- public class TestPrimeNumber {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- if (PrimeNumber.isPrimeNumber(n)) {
- System.out.println(n + " is a prime number.");
- } else {
- System.out.println(n + " is not a prime number.");
- }
- }
- }
□ 実行結果
$ java TestPrimeNumber 7 <-- 素数の場合、 7 is a prime number. $ java TestPrimeNumber 8 <-- 素数でない場合、 8 is not a prime number.
- public class PrimeNumber10 {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- System.out.println();
- }
- }
□ 実行結果
$ java PrimeNumber10 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
□ カプセル化前のBook.java
- public class Book {
- String title; // 書名
- String author; // 著作者
- }
□ カプセル化後のBook.javaクラスをテストするアプリケーションBookTest.java
- public class BookTest {
- public static void main(String[] args) {
- Book b1 = new Book();
- b1.setTitle(args[0]);
- b1.setAuthor(args[1]);
- System.out.println(" Title:" + b1.getTitle());
- System.out.println("Author:" + b1.getAuthor());
- }
- }
□ 実行結果
$ java BookTest JavaBook Maruno Title:JavaBook Author:Maruno
- public class JankenTe {
- // ここにコードを記述してください。
- }
□ JankenTe.javaクラスをテストするアプリケーションJankenAppl.java
- public class JankenAppl {
- public static void main(String[] args) {
- JankenTe te = new JankenTe();
- te.setTe(Integer.parseInt(args[0]));
- System.out.println("手: " + te.getTe());
- }
- }
□ 実行結果
$ java JankenAppl 0 手: 0 $ java JankenAppl 1 手: 1 $ java JankenAppl 2 手: 2 $ java JankenAppl 3 手: 0
- public class JankenTe {
- // ここにコードを記述してください。
- }
□ JankenTe.javaクラスをテストするアプリケーションJankenAppl.java
- public class JankenAppl {
- public static void main(String[] args) {
- JankenTe te = new JankenTe();
- te.setTe(args[0]);
- System.out.println("手: " + te.getTe());
- }
- }
□ 実行結果
$ java JankenAppl ぐー 手: 0 $ java JankenAppl ちょき 手: 1 $ java JankenAppl ぱー 手: 2 $ java JankenAppl ちゃー 手: 0
Shikaku(int x0, int y0, int x1, int y1) | 左上の座標(x0, y0)と右下の座標(x1, y1)。デフォルトの名前は、"四角形"とします。 |
Shikaku(String name, int x0, int y0, int x1, int y1) | 四角形の名前と左上の座標(x0, y0)、右下の座標(x1, y1) |
このクラスには、四角形の周の長さを戻すメソッドlength()を作成してください。周の長さは、つぎの式によります。
四角形 2 * (x1 - x0 + y1 - y0)
- public class Shikaku {
- private int x0, y0; // 左上の頂点の座標
- private int x1, y1; // 左上の頂点の座標
- private int w, h; // 幅と高さ
- private String name; // 名前
- public Shikaku(String name, int x0, int y0, int x1, int y1) { // コンストラクター
- setName(name);
- this.x0 = x0;
- this.y0 = y0;
- this.x1 = x1;
- this.y1 = y1;
- w = Math.abs(x0 - x1);
- h = Math.abs(y0 - y1);
- }
- public Shikaku(int x0, int y0, int x1, int y1) { // コンストラクター
- this("四角形", x0, y0, x1, y1);
- }
- public String getName() { // 名前の取得
- return name;
- }
- public void setName(String name) { // 名前の設定
- this.name = name;
- }
- public double length() { // 周の長さ
- // ここにコードを記述してください。
- }
- }
なお、これらをテストするアプリケーション"ZukeiTest01.java"は、以下のとおりです。
- public class ZukeiTest01 {
- public static void main(String[] args) {
- int x0 = Integer.parseInt(args[0]);
- int y0 = Integer.parseInt(args[1]);
- int x1 = Integer.parseInt(args[2]);
- int y1 = Integer.parseInt(args[3]);
- Shikaku s0 = new Shikaku(x0, y0, x1, y1);
- System.out.println(s0.getName() + " の周の長さ = " + (int)(s0.length()));
- Shikaku s1 = new Shikaku("しかく", x0, y0, x1, y1);
- System.out.println(s1.getName() + " の周の長さ = " + (int)(s1.length()));
- }
- }
□ 実行結果
$ java ZukeiTest01 0 0 100 100 四角形 の周の長さ = 400 しかく の周の長さ = 400
■ コンストラクター
- public class ArgsUtil {
- public static boolean isValid(int count, String[] args, String message) {
- // ここにコードを記述してください。
- }
- public static boolean isValid(int lcount, int hcount, String[] args, String message) {
- if (args.length < lcount || args.length > hcount) {
- System.err.println(message);
- return false;
- }
- return true;
- }
- }
- public class ArgsTest {
- public static void main(String[] args) {
- System.out.println("args.length=1: " +
- ArgsUtil.isValid(1, args, "引数をひとつ指定してください。"));
- System.out.println("1<=args.length<=3: " +
- ArgsUtil.isValid(1, 3, args, "ひとつ以上3つ以下の引数を指定してください。"));
- for (int i = 0; i < args.length; i++) {
- System.out.println("引数: " + args[i]);
- }
- }
- }
□ 実行結果
$ java Args java ArgsTest 引数をひとつ指定してください。 args.length=1: false ひとつ以上3つ以下の引数を指定してください。 1<=args.length<=3: false $ java ArgsTest Hello args.length=1: true 1<=args.length<=3: true 引数: Hello $ java ArgsTest Hello Java World 引数をひとつ指定してください。 args.length=1: false 1<=args.length<=3: true 引数: Hello 引数: Java 引数: World $ java ArgsTest Hello Java Java World 引数をひとつ指定してください。 args.length=1: false ひとつ以上3つ以下の引数を指定してください。 1<=args.length<=3: false 引数: Hello 引数: Java 引数: Java 引数: World
- public class Histogram {
- public static void main(String[] args) {
- Graph g = new Graph();
- for (int i = 0; i < 10; i++) {
- // コードを記述してください。
- }
- }
- }
□ 実行結果
$ java Histogram 9|********* 4|**** 8|******** 7|******* 0| 8|******** 6|****** 8|******** 5|***** 4|****
- public class GCD {
- public int getGCD(String a, String b) {
- // コードを記述してください。
- }
- public int getGCD(int a, int b) {
- int r;
- while ((r = a % b) != 0) {
- a = b;
- b = r;
- }
- return b;
- }
- }
- public class TestGCD {
- public static void main(String[] args) {
- GCD gcd = new GCD();
- System.out.println(args[0] + " と " + args[1] + " の最大公約数は, " + gcd.getGCD(args[0], args[1]) + " です。" );
- }
- }
□ 実行結果
$ java TestGCD 12 32 12 と 32 の最大公約数は, 4 です。
- public class Book {
- private String title; // 書名
- private String author; // 著作者
- // コンストラクター
- // コードを記述してください。
- // title のゲッター
- public String getTitle() {
- return this.title;
- }
- // author のゲッター
- public String getAuthor() {
- return this.author;
- }
- // title のセッター
- public void setTitle(String title) {
- this.title = title;
- }
- // author のセッター
- public void setAuthor(String author) {
- this.author = author;
- }
- }
□ Book.javaクラスをテストするアプリケーションBookTest.java
- public class BookTest {
- public static void main(String[] args) {
- Book b1 = new Book(args[0], args[1]);
- System.out.println(" Title:" + b1.getTitle());
- System.out.println("Author:" + b1.getAuthor());
- }
- }
□ 実行結果
$ java BookTest JavaBook Maruno Title:JavaBook Author:Maruno
- public class JankenTe {
- private int te; // 手
- static final String[] TE_NAMAE = {"ぐー", "ちょき", "ぱー"};
- // コンストラクター
- // コードを記述してください。
- // te のセッター
- public void setTe(String te) {
- for (int i = 0; i < TE_NAMAE.length; i++) {
- if (TE_NAMAE[i].equals(te)) {
- this.te = i;
- return;
- }
- }
- this.te = 0;
- }
- // te のセッター
- public void setTe(int te) {
- if (!(te == 0 || te == 1 || te == 2)) {
- this.te = 0;
- return;
- }
- this.te = te;
- }
- // te のゲッター
- public int getTe() {
- return this.te;
- }
- }
□ JankenTe.javaクラスをテストするアプリケーションJankenAppl.java
- public class JankenAppl {
- public static void main(String[] args) {
- int n = Integer.parseInt(args[0]);
- JankenTe te1 = new JankenTe(n);
- JankenTe te2 = new JankenTe(JankenTe.TE_NAMAE[n]);
- System.out.println("手1: " + te1.getTe());
- System.out.println("手2: " + te2.getTe());
- }
- }
□ 実行結果
$ java JankenAppl 0 手1: 0 手2: 0 $ java JankenAppl 1 手1: 1 手2: 1 $ java JankenAppl 2 手1: 2 手2: 2
- public class JankenTe {
- private int te; // 手
- static final String[] TE_NAMAE = {"ぐー", "ちょき", "ぱー"};
- // コンストラクター
- public JankenTe(String te) {
- setTe(te);
- }
- public JankenTe(int te) {
- setTe(te);
- }
- // te のセッター
- public void setTe(String te) {
- for (int i = 0; i < TE_NAMAE.length; i++) {
- if (TE_NAMAE[i].equals(te)) {
- this.te = i;
- return;
- }
- }
- this.te = 0;
- }
- // te のセッター
- public void setTe(int te) {
- if (!(te == 0 || te == 1 || te == 2)) {
- this.te = 0;
- return;
- }
- this.te = te;
- }
- // te のゲッター
- public int getTe() {
- return this.te;
- }
- // オブジェクトの文字列化
- public String toString() {
- // コードを記述してください。
- }
- // じゃんけん
- public char janken(JankenTe te) {
- final char[][] KEKKA = {{'分', '勝', '負'} // ぐー
- , {'負', '分', '勝'} // ちょき
- , {'勝', '負', '分'}}; // ぱー
- //コンピューター ぐー ちょき ぱー
- // コードを記述してください。
- }
- }
□ JankenTe.javaクラスをテストするアプリケーションJankenAppl.java
- public class JankenAppl {
- public static void main(String[] args) {
- JankenTe user = new JankenTe(args[0]);
- JankenTe computer = new JankenTe((int)(Math.random() * 3));
- System.out.print("結果: " + user.janken(computer));
- System.out.print(", user = " + user.toString());
- System.out.println(", computer = " + computer.toString());
- }
- }
□ 実行結果
$ java JankenAppl ぐー 結果: 分, user = ぐー, computer = ぐー $ java JankenAppl ぐー 結果: 勝, user = ぐー, computer = ちょき $ java JankenAppl ぐー 結果: 負, user = ぐー, computer = ぱー
■ クラスの継承
- public class Book {
- private String title; // 書名
- private String author; // 著作者
- // コンストラクター
- public Book(String title, String author) {
- setTitle(title);
- setAuthor(author);
- }
- // title のゲッター
- public String getTitle() {
- return this.title;
- }
- // author のゲッター
- public String getAuthor() {
- return this.author;
- }
- // title のセッター
- public void setTitle(String title) {
- this.title = title;
- }
- // author のセッター
- public void setAuthor(String author) {
- this.author = author;
- }
- }
- public class SeriesBook extends Book {
- // コードを記述してください。
- }
- public class Magazine extends Book {
- // コードを記述してください。
- }
□ SeriesBook.javaクラス、Magazine.java クラスをテストするアプリケーションBookTest.java
(*) new java.util.Date().toString() は、現在日時の文字列表現をあらわします。
- public class BookTest {
- public static void main(String[] args) {
- Book b1 = new Book(args[0], args[1]);
- System.out.println("Book1 = [" + b1.getTitle() + ", " + b1.getAuthor() + "]");
- SeriesBook b2 = new SeriesBook(args[0], args[1], args[2], Integer.parseInt(args[3]));
- System.out.print("Book2 = [" + b2.getTitle() + ", " + b2.getAuthor());
- System.out.println(", " + b2.getSeries() + ", " + b2.getVolume() + "]");
- Magazine b3 = new Magazine(args[0], args[1], new java.util.Date().toString()(*));
- System.out.print("Book3 = [" + b3.getTitle() + ", " + b3.getAuthor());
- System.out.println(", " + b3.getDate() + "]");
- }
- }
□ 実行結果
$ java BookTest JavaBook Maruno Java 3 Book1 = [JavaBook, Maruno] Book2 = [JavaBook, Maruno, Java, 3] Book3 = [JavaBook, Maruno, Wed Jun 22 21:28:12 JST 2005]
SeriesBook.java ... "シリーズ名 - 書名 (通番)" Magazine.java ... "書名 (日付)"
□ 実行結果
$ java BookTest JavaBook Maruno Java 3 Book1 = [JavaBook, Maruno] Book2 = [JavaBasic - JavaBook (3), Maruno, JavaBasic, 3] Book3 = [JavaBook (Thu Jun 23 12:41:09 JST 2005), Maruno, Thu Jun 23 12:41:09 JST 2005]
図 図形クラス階層
この図形クラスを継承して円、三角形、四角形の図形を処理するクラスを作ります。コンストラクターはつぎのとおりです。なお、図形の座標の原点は左上にあるものとします。
- public class Zukei {
- private String name; // 名前
- public String getName() { // 名前の取得
- return name;
- }
- public void setName(String name) { // 名前の設定
- this.name = name;
- }
- public double length() { // 周の長さ
- return 0.0;
- }
- }
|
Maru(String name, int x, int y, int r) | 中心(x, y)と半径r |
Maru(int x, int y, int r) | 中心(x, y)と半径r | |
|
Sankaku(String name, int[][] p) | 頂点の座標(x0, y0),(x1, y1), (x2, y2)の組 |
Sankaku(int[][] p) | 頂点の座標(x0, y0),(x1, y1), (x2, y2)の組 | |
|
Shikaku(String name, int x0, int y0, int x1, int y1) | 左上の座標(x0, y0)と右下の座標(x1, y1) |
Shikaku(int x0, int y0, int x1, int y1) | 左上の座標(x0, y0)と右下の座標(x1, y1) |
また、図形の周の長さを戻すメソッドlength()をオーバーライドしてください。周の長さは、つぎの式によります。Math.PIは、Mathクラスのdouble型定数で、円周率をあらわします。
円 2 * Math.PI * r 四角形 2 * (x1 - x0 + y1 - y0)
なお、これらをテストするアプリケーション"ZukeiTest01.java"と、三角形クラス"Sankaku.java"のサンプル・ソース・ファイルをつけます。
- public class ZukeiTest01 {
- public static void main(String[] args) {
- Zukei[] z = {
- new Shikaku("基準四角", 0, 0, 100, 100)
- , new Sankaku("基準三角", new int[][]{{0, 0}, {0, 100}, {100, 0}})
- , new Maru("基準丸", 0, 0, 100)
- , new Sankaku(new int[][]{{100, 100}, {10, 250}, {300, 300}})
- , new Maru(150, 170, 60)
- , new Shikaku(120, 130, 300, 190)
- };
- for (int i = 0; i < z.length; i++) {
- System.out.println(z[i].getName() + " の周の長さ = " + Math.round(z[i].length()));
- }
- }
- }
- public class Maru extends Zukei {
- private int x0, y0; // 中心
- private int r; // 半径
- public Maru(String name, int x0, int y0, int r) {
- setName(name);
- this.x0 = x0;
- this.y0 = y0;
- this.r = r;
- }
- public Maru(int x0, int y0, int r) {
- this("丸", x0, y0, r);
- }
- public double length() { // 周の長さ
- // ここにコードを記述してください。
- }
- }
- public class Sankaku extends Zukei {
- private int[][] p; // 頂点
- private double[] l = new double[3]; // 辺の長さ
- public Sankaku(int[][] p) {
- this("三角形", p);
- }
- public Sankaku(String name, int[][] p) {
- setName(name);
- this.p = p;
- for (int i = 0; i < l.length; i++) {
- l[i] = distance(p[i], p[(i + 1) % l.length]);
- }
- }
- public double length() { // 周の長さ
- return sum(l);
- }
- private double sum(double[] x) { // 要素値の合計
- double s = 0;
- for (int i = 0; i < l.length; i++) {
- s += l[i];
- }
- return s;
- }
- private double distance(int[] x, int[] y) { // 頂点間の距離
- return Math.sqrt(sq(diff(x[0], y[0])) + sq(diff(x[1], y[1])));
- }
- private int sq(int x) { // 2乗
- return x * x;
- }
- private int diff(int x, int y) { // 差
- return Math.abs(y - x);
- }
- }
- public class Shikaku extends Zukei {
- private int x0, y0; // 左上の頂点の座標
- private int x1, y1; // 左上の頂点の座標
- private int w, h; // 幅と高さ
- public Shikaku(String name, int x0, int y0, int x1, int y1) { // コンストラクター
- setName(name);
- this.x0 = x0;
- this.y0 = y0;
- this.x1 = x1;
- this.y1 = y1;
- w = Math.abs(x0 - x1);
- h = Math.abs(y0 - y1);
- }
- public Shikaku(int x0, int y0, int x1, int y1) { // コンストラクター
- this("四角形", x0, y0, x1, y1);
- }
- public double length() { // 周の長さ
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java ZukeiTest01 基準四角 の周の長さ = 400 基準三角 の周の長さ = 341 基準丸 の周の長さ = 628 三角形 の周の長さ = 752 丸 の周の長さ = 377 四角形 の周の長さ = 480
■ 参照型の配列
- public class EvenOdd03 {
- public static void main(String[] args) {
- int a = Integer.parseInt(args[0]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java EvenOdd03 10 10は偶数です。 $ java EvenOdd03 11 11は奇数です。
■ 抽象クラス
図 図形クラス階層
- public abstract class Zukei {
- private String name; // 名前
- public String getName() { // 名前の取得
- return name;
- }
- public void setName(String name) { // 名前の設定
- this.name = name;
- }
- public abstract double length() ; // 周の長さ
- }
□ 実行結果
$ java ZukeiTest01 基準四角 の周の長さ = 400 基準三角 の周の長さ = 341 基準丸 の周の長さ = 628 三角形 の周の長さ = 752 丸 の周の長さ = 377 四角形 の周の長さ = 480
■ インターフェース
図 図形クラス階層
インターフェースが実装するのは、以下のメソッドです。
上記インターフェースを利用して、図形を描画するクラスを作成してください。
|
Maru(int x, int y, int r) | 中心(x, y)と半径r |
|
Sankaku(int[][] p) | 頂点の座標(x0, y0),(x1, y1), (x2, y2)の組 |
|
Shikaku(int x0, int y0, int x1, int y1) | 左上の座標(x0, y0)と右下の座標(x1, y1) |
□ "ZukeiTest01.java"は、変更ありません。
- public class Sankaku extends AbstractZukei {
- private int[][] p;
- private double[] l = new double[3]; // 辺の長さ
- public Sankaku(int[][] p) {
- this("三角形", p);
- }
- public Sankaku(String name, int[][] p) {
- setName(name);
- this.p = p;
- for (int i = 0; i < l.length; i++) {
- l[i] = distance(p[i], p[(i + 1) % l.length]);
- }
- }
- public double length() {
- return distance(p[0], p[1]) + distance(p[1], p[2]) + distance(p[2], p[0]);
- }
- private double distance(int[] x, int[] y) {
- return Math.sqrt(diff(x[0], y[0]) * diff(x[0], y[0]) + diff(x[1], y[1]) * diff(x[1], y[1]));
- }
- private double diff(int x, int y) {
- return Math.abs(y - x);
- }
- }
□ 実行結果
$ java ZukeiTest01 基準四角 の周の長さ = 400 基準三角 の周の長さ = 341 基準丸 の周の長さ = 628 三角形 の周の長さ = 752 丸 の周の長さ = 377 四角形 の周の長さ = 480
■ パッケージ
$ mkdir -p maruno/classes maruno/sources
- package com.maruno.mypack;
- public class Pack01 {
- public void printData() {
- System.out.println( "Pack01" );
- }
- }
□ コンパイル
$ javac -d ../classes Pack01.java
- import com.maruno.mypack.Pack01;
- public class Pack02 {
- public static void main( String[] args ) {
- Pack01 pack01;
- pack01 = new Pack01();
- pack01.printData();
- }
- }
□ コンパイル
$ javac -classpath ../classes Pack02.java
□ 実行結果
$java -cp .:../classes com.maruno.mypack.Pack02 Pack01
■ 例外処理
- public class Exception30 {
- public static void main(String[] args) {
- System.out.println("*** start ***");
- int a = Integer.parseInt(args[0]);
- System.out.println(100 / a);
- System.out.println("*** end ***");
- }
- }
□ 実行結果
$ java Exception30 *** start *** Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Exception30.main(Exception30.java:4) $ java Exception30 Hello *** start *** Exception in thread "main" java.lang.NumberFormatException: For input string: "Hello" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at Exception30.main(Exception30.java:4) $ java Exception30 0 *** start *** Exception in thread "main" java.lang.ArithmeticException: / by zero at Exception30.main(Exception30.java:5) $ java Exception30 20 *** start *** 5 *** end ***
- public class String50 {
- public static void main(String[] args) {
- String s1 = "Hello";
- String s2 = "Hello";
- String s3 = new String("Hello");
- String s4 = new String("Hello");
- System.out.println("s1 == s2: " + (s1 == s2));
- System.out.println("s1 == s3: " + (s1 == s3));
- System.out.println("s1 == s4: " + (s1 == s4));
- System.out.println("s3 == s4: " + (s3 == s4));
- System.out.println("s1.equals(s2): " + (s1.equals(s2)));
- System.out.println("s1.equals(s3): " + (s1.equals(s3)));
- System.out.println("s1.equals(s4): " + (s1.equals(s4)));
- System.out.println("s3.equals(s4): " + (s3.equals(s4)));
- }
- }
□ 実行結果
$ java String50 s1 == s2: true s1 == s3: false s1 == s4: false s3 == s4: false s1.equals(s2): true s1.equals(s3): true s1.equals(s4): true s3.equals(s4): true
- public class String52 {
- public static void main(String[] args) {
- String s = "Hello Java World";
- System.out.println(" 0123456789012345");
- System.out.println("s = " + s );
- System.out.println("s.length() = " + s.length() );
- System.out.println("s.charAt(6) = " + s.charAt(6) );
- System.out.println("s.indexOf(\"x\") = " + s.indexOf("x") );
- System.out.println("s.indexOf(\"l\") = " + s.indexOf("l") );
- System.out.println("s.indexOf(\"l\", 6) = " + s.indexOf("l", 6) );
- System.out.println("s.matches(\".*Java.*\") = " + s.matches(".*Java.*") );
- System.out.println("s.substring(2, 5) = " + s.substring(2, 5) );
- System.out.println("s.substring(11, 15) = " + s.substring(11, 15));
- System.out.println("s.substring(11, 16) = " + s.substring(11, 16));
- System.out.println("s.substring(11) = " + s.substring(11) );
- System.out.println("s.toLowerCase() = " + s.toLowerCase() );
- System.out.println("s.toUpperCase() = " + s.toUpperCase() );
- System.out.println("s.replaceAll(\"Hello\", \"Hi\") = " + s.replaceAll("Hello", "Hi"));
- String[] sa = s.split(" ");
- for (int i = 0; i < sa.length; i++) {
- System.out.println("s.split(\" \")[" + i + "] = " + sa[i]);
- }
- }
- }
□ 実行結果
$ java String52 0123456789012345 s = Hello Java World s.length() = 16 s.charAt(6) = J s.indexOf("x") = -1 s.indexOf("l") = 2 s.indexOf("l", 6) = 14 s.matches(".*Java.*") = true s.substring(2, 5) = llo s.substring(11, 15) = Worl s.substring(11, 16) = World s.substring(11) = World s.toLowerCase() = hello java world s.toUpperCase() = HELLO JAVA WORLD s.replaceAll("Hello", "Hi") = Hi Java World s.split(" ")[0] = Hello s.split(" ")[1] = Java s.split(" ")[2] = World
- public class String60 {
- public static void main(String[] args) {
- int i = -1;
- while (/* ここにコードを書いてください。*/) {
- System.out.println(i);
- }
- }
- }
□ 実行結果
$ java String60 "hello world" l 2 3 9
□ 実行結果
$ java String601 "HELLO world" l 2 3 9
- public class String61 {
- public static void main(String[] args) {
- int i = -1;
- while ( /* ここにコードを書いてください。*/ ) {
- // ここにコードを書いてください。
- }
- }
- }
□ 実行結果
$ java String61 "Hello World" l He l lo World Hel l o World Hello Wor l d
- public class StringBuffer50 {
- public static void main(String[] args) {
- StringBuffer sb1 = new StringBuffer("Hello");
- StringBuffer sb2 = sb1;
- sb1.append(" World!");
- System.out.println("sb1 == sb2 ? " + (sb1 == sb2));
- }
- }
□ 実行結果
$ java StringBuffer50 sb1 == sb2 ? true
- public class StringBuffer51 {
- public static void main(String[] args) {
- StringBuffer sb1 = new StringBuffer("Hello");
- System.out.println(" sb1 = " + sb1);
- sb1.append(" World!");
- System.out.println(" sb1.append(\" World!\") = " + sb1);
- sb1.insert(5, " Java");
- System.out.println(" sb1.insert(5, \" Java\") = " + sb1);
- sb1.replace(6, 10, "Servlet");
- System.out.println("sb1.replace(6, 10, \"Servlet\") = " + sb1);
- sb1.reverse();
- System.out.println(" sb1.reverse() = " + sb1);
- }
- }
□ 実行結果
$ java StringBuffer51 sb1 = Hello sb1.append(" World!") = Hello World! sb1.insert(5, " Java") = Hello Java World! sb1.replace(6, 10, "Servlet") = Hello Servlet World! sb1.reverse() = !dlroW telvreS olleH
- public class StringBuffer10 {
- public static void main(String[] args) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < args.length; i++) {
- // ここにコードを書いてください。
- }
- System.out.println(sb);
- }
- }
□ 実行結果
$ java StringBuffer10 Hello Java World World Java Hello
□ 実行結果
実行結果 $ java StringBuffer11 Hello Java World dlroW avaJ olleH
- public class StringBuffer20 {
- public static void main(String[] args) {
- StringBuffer sb = new StringBuffer(args[0]);
- int i;
- while ((i = sb.indexOf(args[1])) > -1) {
- // ここにコードを書いてください。
- }
- System.out.println(sb);
- }
- }
□ 実行結果
$ java StringBuffer20 "hello world, java, and hello to you all" hello hi hi world, java, and hi to you all
■ ラッパー・クラス
- public class Wrapper51 {
- public static void main(String[] args) {
- byte a = /* ここにコードを記述してください。*/ (args[0]);
- byte b = /* ここにコードを記述してください。*/ (args[1]);
- // ここにコードを記述してください。
- }
- }
□ 実行結果
$ java Wrapper51 10 2 20はbyte型の範囲内です。 $ java Wrapper51 10 20 200はbyte型に収まりません。結果は、-56
■ コレクション
- import java.util.*;
- public class ArrayList002 {
- public static void main(String[] args) {
- List al = new ArrayList();
- for (int i = 0; i < args.length; i++) {
- al.add(new Double(args[i]));
- }
- System.out.println(al);
- }
- }
□ 実行結果
$ >java ArrayList002 5 -3 1 -2 4 [5.0, -3.0, 1.0, -2.0, 4.0]
- import java.util.*;
- public class ArrayList13 {
- public static void main( String[] args ) {
- List al = new ArrayList();
- for ( int i = 0; i < 10; i++ ) {
- al.add(new Integer(i));
- }
- System.out.println("before: " + al);
- for ( int i = 0; i < 2; i++ ) {
- // ここにコードを追加してください。
- }
- System.out.println("after: " + al);
- }
- }
□ 実行結果
$ java ArrayList13 before: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] after: [2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
0101 | 丸野 | maruno@abc.co.jp |
0201 | 山田 | yamada@def.com |
0202 | 鈴木 | suzuki@def.com |
0102 | 佐藤 | sato@abc.co.jp |
- public class EmailList {
- String id;
- String name;
- String email;
- EmailList(String id, String name, String email) {
- this.id = id;
- this.name = name;
- this.email = email;
- }
- }
- import java.util.*;
- public class EmailManage01 {
- public static void main(String[] args) {
- Map emailObject = new HashMap();
- // emailObject の設定
- final String[][] EMAIL_LIST = {
- {"0101", "丸野", "maruno@abc.co.jp"}
- , {"0201", "山田", "yamada@def.com"}
- , {"0202", "鈴木", "suzuki@def.com"}
- , {"0102", "佐藤", "sato@abc.co.jp"}
- };
- for (int i = 0; i < EMAIL_LIST.length; i++) {
- emailObject.put(EMAIL_LIST[i][0],
- new EmailList(EMAIL_LIST[i][0], EMAIL_LIST[i][1], EMAIL_LIST[i][2]));
- }
- // emailObject の検索
- if (/* ここにコードを記述してください */) {
- EmailList el = (EmailList)emailObject.get(args[0]);
- System.out.println("id = " + args[0]);
- System.out.println("name = " + el.name);
- System.out.println("email = " + el.email);
- } else {
- System.out.println("id = " + args[0] + " はありませんでした。");
- }
- }
- }
□ 実行結果
$ java EmailManage01 0102 id = 0102 name = 佐藤 email = sato@abc.co.jp $ java EmailManage01 0203 id = 0203 はありませんでした。
□ email名簿クラス("EmailList.java", 変更ありません)
- public class EmailList {
- String id;
- String name;
- String email;
- public EmailList(String id, String name, String email) {
- this.id = id;
- this.name = name;
- this.email = email;
- }
- public String toString() {
- return "[" + id + ", " + name + ", " + email + "]";
- }
- }
□ email管理クラス("EmailManage03.java")
- import java.util.*;
- public class EmailManage03 {
- public static void main(String[] args) {
- Map emailObject = new HashMap(); // email リスト
- Map emailIndex = new HashMap(); // name と id を対応づける Map
- /*
- * emailIndex emailObject
- * name id id name email
- * ---- ---- ---- ---- -----------------
- * 丸野 0101 0101 丸野 maruno@abc.co.jp
- * 山田 0201 0201 山田 yamada@def.com
- * 鈴木 0202 0202 鈴木 suzuki@def.com
- * 佐藤 0102 0102 佐藤 sato@abc.co.jp
- */
- // emailObject の設定
- final String[][] EMAIL_LIST = { { "0101", "丸野", "maruno@abc.co.jp" },
- { "0201", "山田", "yamada@def.com" },
- { "0202", "鈴木", "suzuki@def.com" },
- { "0102", "佐藤", "sato@abc.co.jp" } };
- for (int i = 0; i < EMAIL_LIST.length; i++) {
- emailObject.put(EMAIL_LIST[i][0], new EmailList(EMAIL_LIST[i][0],
- EMAIL_LIST[i][1], EMAIL_LIST[i][2]));
- emailIndex.put(EMAIL_LIST[i][1], EMAIL_LIST[i][0]); // インデックスの設定
- }
- // emailObject の検索
- if (emailObject.containsKey(emailIndex.get(args[0]))) {
- // ここにコードを追加してください。
- System.out.println("id = " + el.id);
- System.out.println("name = " + el.name);
- System.out.println("email = " + el.email);
- } else {
- System.out.println("name = " + args[0] + " はありませんでした。");
- }
- }
- }
□ 実行結果
$ java EmailManage03 山田 id = 0201 name = 山田 email = yamada@def.com $ java EmailManage03 山本 name = 山本 はありませんでした。
照会 | なし または Q |
java EmailManage02 0101 または java EmailManage02 Q 0101 |
---|---|---|
追加 / 変更 | A / U |
java EmailManage02 A 0109 田中 tanaka@ghi.co.jp |
削除 | D |
java EmailManage02 D 0101 |
□ email名簿クラス("EmailList.java")
- public class EmailList {
- String id;
- String name;
- String email;
- public EmailList(String id, String name, String email) {
- this.id = id;
- this.name = name;
- this.email = email;
- }
- public String toString() {
- return "[" + id + ", " + name + ", " + email + "]";
- }
- }
□ email管理クラス("EmailManage02.java")
- import java.util.*;
- public class EmailManage02 {
- static Map emailObject = new HashMap();
- public static void main(String[] args) {
- // emailObject の設定
- final String[][] EMAIL_LIST = {
- {"0101", "丸野", "maruno@abc.co.jp"}
- , {"0201", "山田", "yamada@def.com"}
- , {"0202", "鈴木", "suzuki@def.com"}
- , {"0102", "佐藤", "sato@abc.co.jp"}
- };
- for (int i = 0; i < EMAIL_LIST.length; i++) {
- emailObject.put(EMAIL_LIST[i][0],
- new EmailList(EMAIL_LIST[i][0], EMAIL_LIST[i][1], EMAIL_LIST[i][2]));
- }
- System.out.println("emailObject = " + emailObject);
- // 処理の切り分け
- switch (args[0].charAt(0)) {
- case 'q':
- case 'Q':
- queryEmailObject(args[1]);
- break;
- case 'd':
- case 'D':
- deleteEmailObject(args[1]);
- break;
- case 'a':
- case 'A':
- case 'u':
- case 'U':
- addEmailObject(args[1], args[2], args[3]);
- break;
- default:
- queryEmailObject(args[0]);
- break;
- }
- System.out.println("emailObject = " + emailObject);
- }
- // emailObject の照会
- static void queryEmailObject(String id) {
- // ここにコードを追加してください。
- }
- // emailObject の削除
- static void deleteEmailObject(String id) {
- // ここにコードを追加してください。
- }
- // emailObject の追加 / 変更
- static void addEmailObject(String id, String name, String email) {
- // ここにコードを追加してください。
- }
- }
□ 実行結果
$ java EmailManage02 0101 emailObject = {0101=[0101, 丸野, maruno@abc.co.jp], 0202=[0202, 鈴木, suzuki@def .com], 0102=[0102, 佐藤, sato@abc.co.jp], 0201=[0201, 山田, yamada@def.com]} id = 0101 name = 丸野 email = maruno@abc.co.jp emailObject = {0101=[0101, 丸野, maruno@abc.co.jp], 0202=[0202, 鈴木, suzuki@def .com], 0102=[0102, 佐藤, sato@abc.co.jp], 0201=[0201, 山田, yamada@def.com]} $ java EmailManage02 q 0101 emailObject = {0101=[0101, 丸野, maruno@abc.co.jp], 0202=[0202, 鈴木, suzuki@def .com], 0102=[0102, 佐藤, sato@abc.co.jp], 0201=[0201, 山田, yamada@def.com]} id = 0101 name = 丸野 email = maruno@abc.co.jp emailObject = {0101=[0101, 丸野, maruno@abc.co.jp], 0202=[0202, 鈴木, suzuki@def .com], 0102=[0102, 佐藤, sato@abc.co.jp], 0201=[0201, 山田, yamada@def.com]} $ java EmailManage02 d 0101 emailObject = {0101=[0101, 丸野, maruno@abc.co.jp], 0202=[0202, 鈴木, suzuki@def .com], 0102=[0102, 佐藤, sato@abc.co.jp], 0201=[0201, 山田, yamada@def.com]} id = 0101 を削除しました。 emailObject = {0202=[0202, 鈴木, suzuki@def.com], 0102=[0102, 佐藤, sato@abc.co. jp], 0201=[0201, 山田, yamada@def.com]} $ java EmailManage02 a 0901 田中 tanaka@ghi.co.jp emailObject = {0101=[0101, 丸野, maruno@abc.co.jp], 0202=[0202, 鈴木, suzuki@def .com], 0102=[0102, 佐藤, sato@abc.co.jp], 0201=[0201, 山田, yamada@def.com]} id = 0901 を追加しました。 emailObject = {0101=[0101, 丸野, maruno@abc.co.jp], 0202=[0202, 鈴木, suzuki@def .com], 0102=[0102, 佐藤, sato@abc.co.jp], 0201=[0201, 山田, yamada@def.com], 090 1=[0901, 田中, tanaka@ghi.co.jp]}
- import java.io.*;
- public class FileIO011 {
- public static void main( String[] args ) {
- int b;
- FileInputStream fis = null;
- FileOutputStream fos = null;
- // ここにコードを記述してください。
- }
- }
$ java FileIO11 Stream.dat Stream.copy A A-- 出力ファイル名 +-- 入力ファイル名 $ diff Stream.dat Stream.copy <-- 差があるか否かの確認(なければメッセージなし)
$ java FileIO11 Stream.dat Stream.copy A A-- 出力ファイル名 +-- 入力ファイル名 $ dir Stream.* <-- 差があるか否かの確認(サイズで確認)
- import java.io.*;
- public class Encoding04 {
- public static void main(String[] args) {
- FileInputStream fis;
- FileOutputStream fos;
- int key = Integer.parseInt(args[2]);
- int b;
- try {
- fis = new FileInputStream(args[0]);
- fos = new FileOutputStream(args[1]);
- while ((b = fis.read()) != -1) {
- // ここにコードを記述してください。
- }
- fos.close();
- fis.close();
- } catch (IOException e) {
- }
- }
- }
□ 実行結果
$ java Encoding04 sample.txt sample.out 3
■ 文字ストリーム
- import java.io.*;
- public class FileCopy {
- public static void main(String[] args) {
- if (copyFile(args[0], args[1])) {
- System.err.println("File '" + args[0] + "' copied to '" + args[1] + "'.");
- } else {
- System.err.println("File '" + args[0] + "' does not copied.");
- }
- }
- public static boolean copyFile(String inFileName, String outFileName) {
- try {
- // 文字ストリームの獲得(ファイルのオープン)
- BufferedReader br = new BufferedReader(new FileReader(inFileName));
- BufferedWriter bw = new BufferedWriter(new FileWriter(outFileName));
- String str;
- // データの読み込み(入力)
- while ((str = br.readLine()) != null) {
- // 読み込んだデータの書き込み(出力)
- bw.write(str);
- bw.newLine();
- }
- // ストリームのクローズ(ファイルのクローズ)
- bw.flush();
- bw.close();
- br.close();
- } catch (FileNotFoundException e) {
- return false;
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- return true;
- }
- }
□ 実行結果
$ java FileCopy FileCopy.java a.txt File 'FileCopy.java' copied to 'a.txt'.
- import java.io.*;
- public class FileCopy {
- public static void main(String[] args) {
- FileCopy fc = new FileCopy();
- String inf = "", outf = "";
- String ie = // コードを記述してください。
- String oe = // コードを記述してください。
- for (int i = 0; i < args.length; i++) {
- if (args[i].equals("-ie")) {
- ie = args[++i];
- } else if (args[i].equals("-oe")) {
- oe = args[++i];
- } else {
- if (inf.equals("")) {
- inf = args[i];
- } else {
- outf = args[i];
- }
- }
- }
- if (fc.copyFile(ie, oe, inf, outf)) {
- System.err.println("File '" + inf + "(" + ie
- + ")' copied to '" + outf + "(" + oe + ")'.");
- } else {
- System.err.println("File '" + inf + "' does not copied.");
- }
- }
- public boolean copyFile(String inFileEncoding,
- String outFileEncoding,
- String inFileName,
- String outFileName) {
- try {
- // 文字ストリームの獲得(ファイルのオープン)
- BufferedReader br =
- // コードを記述してください。
- BufferedWriter bw =
- // コードを記述してください。
- String str;
- // データの読み込み(入力)
- while ((str = br.readLine()) != null) {
- // 読み込んだデータの書き込み(出力)
- bw.write(str);
- bw.newLine();
- }
- // ストリームのクローズ(ファイルのクローズ)
- bw.flush();
- bw.close();
- br.close();
- } catch (FileNotFoundException e) {
- return false;
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- return true;
- }
□ 実行結果
$ java FileCopy FileCopy.java a.txt File 'Stream.dat(JISAutoDetect)' copied to 'aaa.dat(MS932)'. $ java FileCopy -ie MS932 Stream.dat aaa.dat File 'Stream.dat(JISAutoDetect)' copied to 'aaa.dat(MS932)'.
- import java.io.*;
- public class FileCopy {
- public static void main(String[] args) {
- // 前問と同じ。
- if (outf.equals("")) {
- if (fc.encodeFile(ie, oe, inf)) {
- System.err.println("File '" + inf + "(" + ie
- + ")' encoded to '" + oe + "'.");
- } else {
- System.err.println("File '" + inf
- + "' does not encorded.");
- }
- } else {
- if (fc.copyFile(ie, oe, inf, outf)) {
- // 前問と同じ。
- }
- }
- }
- public boolean encodeFile(String inFileEncoding,
- String outFileEncoding,
- String fileName) {
- String tmpFileName = fileName + ".tmp";
- // コードを記述してください。
- return deleteFile(tmpFileName);
- }
- public boolean deleteFile(String fileName) {
- // コードを記述してください。
- }
- public boolean copyFile(String inFileEncoding,
- String outFileEncoding,
- String inFileName,
- String outFileName) {
- // 前問と同じ。
- }
- }
□ 実行結果
$ java FileCopy -ie EUC_JP aaaa.txt File 'aaaa.txt(EUC_JP)' encoded to 'MS932'.
$ javac -d . FileCopy.java $ jar -cf maruno.jar maruno/*.class $ cp maruno.jar $JAVA_HOME/jre/lib/ext/
□ 実行結果
$ java -cp $JAVA_HOME/jre/lib/ext/maruno.jar maruno.FileCopy -ie EUC_JP aaaa.txt File 'aaaa.txt(EUC_JP)' encoded to 'MS932'.
■ 標準入出力
- import java.io.*;
- public class Sysin2Sysout {
- public static void main (String[] args) {
- int b;
- try {
- while ((b = System.in.read()) != -1) {
- System.out.println("char = " + (char)b + ", hex = " +
- Integer.toHexString(b));
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
□ 実行結果
$ java Sysin2Sysout Hello <-- 入力したデータ char = H, hex = 48 char = e, hex = 65 char = l, hex = 6c char = l, hex = 6c char = o, hex = 6f , hex = d char = , hex = a あいうえお <-- 入力したデータ char = ?, hex = 82 char = ?, hex = a0 char = ?, hex = 82 char = ¢, hex = a2 char = ?, hex = 82 char = ?, hex = a4 char = ?, hex = 82 char = ?, hex = a6 char = ?, hex = 82 char = ¨, hex = a8 , hex = d char = , hex = a
- import java.io.*;
- public class Sysin2SysoutWithJp {
- public static void main (String[] args) {
- BufferedReader sysin
- = new BufferedReader(new InputStreamReader(System.in));
- String str = null;
- try {
- while ((str = sysin.readLine()) != null) {
- System.out.println(str);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
□ 実行結果
$ java Sysin2Sysout 入力データ <-- 入力したデータ 入力データ <-- 出力されたデータ 出力データ <-- 入力したデータ 出力データ <-- 出力されたデータ
□ 実行結果
$ java Sysin2Sysout02 Hello out: Hello err: Hello Java out: Java err: Java World! out: World! err: World!
- import java.io.*;
- public class Sum11 {
- public static void main (String[] args) {
- BufferedReader sysin = /* コードを記述してください。*/ ;
- String str = null;
- int sum = 0;
- try {
- while (/* コードを記述してください。*/) {
- if (/* コードを記述してください。*/) {
- break;
- }
- // コードを記述してください。
- }
- } catch (IOException e) {
- System.out.println("IOException");
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("sum = " + sum);
- }
- }
□ 実行結果
$ java Sum11 22 44 66 -99 q sum = 33
- import java.io.*;
- public class Sum12 {
- public static void main (String[] args) {
- BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
- String str = null;
- int sum = 0;
- try {
- // コードを記述してください。
- } catch (IOException e) {
- System.err.println("IOException");
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("sum = " + sum);
- }
- }
□ 実行結果
$ java Sum12 22 44 rr NumberFormatException for input rr 66 ii NumberFormatException for input ii -99 qq NumberFormatException for input qq q sum = 33
- import java.io.*;
- public class Grep01 {
- public static void main (String[] args) {
- BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
- String str = null;
- try {
- // コードを記述してください。
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
□ 実行結果
$ cat Grep01.java | java Grep01 str String str = null; while ((str = sysin.readLine()) != null) { if (str.matches(".*" + args[0] + ".*")) { System.out.println(str);
- import java.io.*;
- public class Janken01 {
- static BufferedReader br = null;
- public static void main(String[] args) {
- int draw = 0;
- int win = 0;
- int lose = 0;
- try {
- int user = -1;
- br = new BufferedReader(new InputStreamReader(System.in));
- while ((user = read()) != -1) {
- int computer = (int)(Math.random() * 3);
- // コードを記述してください。
- System.err.println(win + " 勝 " + lose + " 敗 " + draw + " 分 ");
- }
- System.out.println();
- System.out.println(win + " 勝 " + lose + " 敗 " + draw + " 分 ");
- }
- catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- br.close();
- } catch (Exception e) {
- }
- }
- }
- public static int read() throws IOException {
- int user = -1;
- while ((user = read("グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> ")) != -1) {
- if (user >= 0 && user <= 3) {
- break;
- }
- }
- return user;
- }
- public static int read(String message) throws IOException {
- System.out.print(message);
- String str = br.readLine();
- if (str == null) {
- return -1;
- }
- int user = -1;
- // コードを記述してください。
- }
- }
□ 実行結果
$ java Janken01 グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> g あなたの勝 1 勝 0 敗 0 分 グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> g あなたの敗け 1 勝 1 敗 0 分 グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> c 引き分け 1 勝 1 敗 1 分 グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> c 引き分け 1 勝 1 敗 2 分 グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> p あなたの勝 2 勝 1 敗 2 分 グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> p あなたの勝 3 勝 1 敗 2 分 グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> d グー(g), チョキ(c), パー(p), 終了(x)を入力してください。==> x 3 勝 1 敗 2 分
- import java.io.*;
- public class NumberGuess01 {
- private static BufferedReader br = null;
- public static void main(String[] args) {
- int computer = getNumber();
- System.err.println("computer = " + computer);
- int[] n = new int[2];
- try {
- br = new BufferedReader(new InputStreamReader(System.in));
- int user;
- int count = 0;
- while ((user = read()) != -1) {
- n = checkNumbers(user, computer);
- if (user == computer) {
- System.out.println("ビンゴ! " + count);
- break;
- }
- System.out.println("桁違いの同じ数 = " + n[0]);
- System.out.println(" 一致した数 = " + n[1]);
- System.out.println();
- }
- }
- catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- br.close();
- } catch (Exception e) {
- }
- }
- }
- public static int[] checkNumbers(int u, int c) {
- // コードを記述してください。
- return n;
- }
- public static int getNumber() {
- // コードを記述してください。
- }
- public static int read() throws IOException {
- int user = -1;
- while ((user = read("2桁-3桁の正整数をを入力してください。==> ")) != -1) {
- if (user >= 10 && user <= 999) {
- break;
- }
- }
- return user;
- }
- public static int read(String message) throws IOException {
- System.out.print(message);
- String str = br.readLine();
- if (str == null) {
- return 0;
- }
- int user = 0;
- try {
- user = Integer.parseInt(str);
- } catch (NumberFormatException e) {
- }
- return user;
- }
- }
□ 実行結果
$ java NumberGuess01 2> null 2桁-3桁の正整数をを入力してください。==> 123 桁違いの同じ数 = 1 一致した数 = 0 2桁-3桁の正整数をを入力してください。==> 124 桁違いの同じ数 = 0 一致した数 = 0 2桁-3桁の正整数をを入力してください。==> 345 桁違いの同じ数 = 0 一致した数 = 1 2桁-3桁の正整数をを入力してください。==> 367 桁違いの同じ数 = 1 一致した数 = 1 2桁-3桁の正整数をを入力してください。==> 378 桁違いの同じ数 = 0 一致した数 = 2 2桁-3桁の正整数をを入力してください。==> 379 ビンゴ! 6Top