Java - 参照型の配列


■ページ目次

Top
■クラス型の配列を作成する
■例題
  1. つぎの"Array02.java"をコンパイル・実行してください。
    1. public class Array02 {
    2. public static void main( String[] args ) {
    3. Sample[] classarray;
    4. classarray = new Sample[3];
    5. for ( int i = 0; i < classarray.length; i++ ) {
    6. classarray[ i ] = new Sample();
    7. classarray[ i ].aaa = i * 10;
    8. System.out.println( "classarray[" + i
    9. + "].aaa" + " = "
    10. + classarray[ i ].aaa );
    11. }
    12. }
    13. }
    14. public class Sample {
    15. int aaa = 0;
    16. }

    □ 実行結果

    $java Array02
    classarray[0].aaa = 0
    classarray[1].aaa = 10
    classarray[2].aaa = 20
    
■実習
  1. コマンドラインから入力した整数が奇数か偶数かを判定してメッセージを出すアプリケーション"EvenOdd03.java"を作成してください。このとき、if文を使わないで作成してください。
    1. public class EvenOdd03 {
    2. public static void main(String[] args) {
    3. int a = Integer.parseInt(args[0]);
    4. // ここにコードを記述してください。
    5. }
    6. }

    □ 実行結果

    $ java EvenOdd03 10
    10は偶数です。
    
    $ java EvenOdd03 11
    11は奇数です。
    
  2. 前に行った"JavaIdentifier02.java"を改良して、コマンドラインから指定された文字列が識別子の条件を満たし、かつ予約語やリテラルを含まないような文字列か否かを判定するアプリケーション"JavaIdentifier03.java"を作成してください。
    1. public class JavaIdentifier03 {
    2. public static boolean isJavaIdentifier(String s) {
    3. String[] keywords = {
    4. "abstract", "assert", "boolean", "break",
    5. "byte", "case", "catch", "char",
    6. "class", "const", "continue", "default",
    7. "do", "double", "else", "extends",
    8. "false", "final", "finally", "float",
    9. "for", "goto", "if", "implements",
    10. "import", "instanceof", "int", "interface",
    11. "long", "native", "new", "null",
    12. "package", "private", "protected", "public",
    13. "return", "short", "static", "strictfp",
    14. "super", "switch", "synchronized", "this",
    15. "throw", "throws", "transient ", "true",
    16. "try", "void", "volatile", "while"
    17. };
    18. if (!Character.isJavaIdentifierStart(s.charAt(0))) {
    19. return false;
    20. }
    21. for (int i = 1; i < s.length(); i++) {
    22. if (!Character.isJavaIdentifierPart(s.charAt(i))) {
    23. return false;
    24. }
    25. }
    26. // ここにコードを追加してください。
    27. }
    28. return true;
    29. }
    30. public static void main(String[] args) {
    31. if (isJavaIdentifier(args[0])) {
    32. System.out.println(args[0] + " is Java Identifier.");
    33. } else {
    34. System.out.println(args[0] + " is not Java Identifier.");
    35. }
    36. }
    37. }

    □ 実行結果

    $ java JavaIdentifier03 True
    True is Java Identifier.
    
    $ java JavaIdentifier03 true
    true is not Java Identifier.
    
Top

■配列の配列を作成する

■実習
Top

■配列初期化子を使った配列の作成

Top

inserted by FC2 system