エンジニア成長日記 swaponQ

コンピュータサイエンス専攻の一般人のブログです。

新・明解 Java 入門 演習 6-1, 6-2, 6-3, 6-4 解答

Hello, Terminal!swaponQです!

お久しぶりです。
今回から「第6章:配列」に入ります。

第6章には演習が19題用意されています!

まずは演習 6-1, 6-2, 6-3, 6-4 に取り組んでいこうと思います。

  • 演習 6-1

要素型がdouble型で要素数が5の配列を生成して、その全要素の値を表示するプログラムを作成せよ。

ソースコード

class ex06_1 {
	public static void main(String[] args) {
		double[] a = new double[5];
		a[0] = 0.0;
		a[1] = 1.0;
		a[2] = 2.0;
		a[3] = 3.0;
		a[4] = 4.0;
		System.out.println("a["+0+"] = "+ a[0]);
		System.out.println("a["+1+"] = "+ a[1]);
		System.out.println("a["+2+"] = "+ a[2]);
		System.out.println("a["+3+"] = "+ a[3]);
		System.out.println("a["+4+"] = "+ a[4]);
	}
}

・実行結果

a[0] = 0.0
a[1] = 1.0
a[2] = 2.0
a[3] = 3.0
a[4] = 4.0
  • 演習 6-2

要素型がint型で要素数が5の配列の要素に対して、先頭から順に5,4,3,2,1を代入して表示するプログラムを作成せよ。

ソースコード

class ex06_2 {
	public static void main(String[] args) {
		int[] a = new int[5];
		for (int i = 0; i < a.length; i++) {
			a[i] = 5 - i;
			System.out.println("a[" + i + "] = " + a[i]);
		}
	}
}

・実行結果

a[0] = 5
a[1] = 4
a[2] = 3
a[3] = 2
a[4] = 1
  • 演習 6-3

要素型がdouble型で要素数が5の配列の要素に対して、先頭から順に1.1,2.2,3.3,4.4,5.5を代入して表示するプログラムを作成せよ。

ソースコード

class ex06_3 {
	public static void main(String[] args) {
		double[] a = new double[5];

		for (int i = 0; i < a.length; i++) {
			int j = i + 1;
			double n = (j * 11);
			a[i] = (double)(n / 10);
			System.out.println(a[i]);
		}
	}
}

・実行結果

1.1
2.2
3.3
4.4
5.5
  • 演習 6-4

List6-5を書きかえて、縦向きの棒グラフで表示するプログラムを作成せよ。最下段には、インデックスを10で割った剰余を表示すること。

ソースコード

import java.util.Random;
import java.util.Scanner;

class ex06_4 {
  public static void main(String[] args) {
    Random rand = new Random();
    Scanner stdIn = new Scanner(System.in);
    System.out.print("要素数:");
    int n = stdIn.nextInt();
    int[] a = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = 1 + rand.nextInt(10);
    }
    //'*'の描画
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < n; j++) {
        if (i >= (10 - a[j])) {
          System.out.print('*');
        } else {
          System.out.print(' ');
        }
        if (j == (n - 1)) {
          System.out.println();
        } else {
          System.out.print(' ');
        }
      }
    }
    //'-'の描画
    for (int i = 0; i < n; i++) {
      System.out.print('-');
      if (i == n - 1) {
        System.out.println();
      } else {
        System.out.print('-');
      }
    }
    //インデックスの描画
    for (int i = 0; i < n; i++) {
      System.out.print(i % 10);
      if (i == n - 1) {
        System.out.println();
      } else {
        System.out.print(' ');
      }
    }
  }
}

・実行結果

要素数:12
                       
                  *    
                  *    
*   *       *     *    
* * *       *     *    
* * *   *   *     *   *
* * *   *   *     * * *
* * *   *   * *   * * *
* * *   *   * * * * * *
* * * * * * * * * * * *
-----------------------
0 1 2 3 4 5 6 7 8 9 0 1



今回は以上です。お疲れ様でした!
次回は演習 6-5, 6-6, 6-7, 6-8 です。

Goodbye, Terminal… swaponQでした!