[ Java練習問題 ] 練習問題 第6回 『配列 ①』

目次

配列基礎 1

Java練習問題 第6回では「配列」についての問題を用意してあります。
「配列」の解説はこちら

問題 1 難易度 ★★

以下の手順で、おみくじプログラムを作成してください。

① 要素数 3 の文字列配列を宣言し、大吉、中吉、凶の三つの文字列を格納。
② 0~2 の 3 通りの数値から、ランダムに一つの数値を生成。
(参考) int random = new java.util.Random().nextInt(3);
③ 生成したランダムな数値をインデックスとする配列の要素を使用して、コンソールにおみくじ結果を出力。

実行例

今日の運勢は「大吉」です。

問題 1 解答

正解は、、、
public class Main_0401 {
  public static void main(String[] args) {
    String[] results = new String[3];
    results[0] = "大吉";
    results[1] = "中吉";
    results[2] = "";
    
    int random = new java.util.Random().nextInt(3);
    System.out.println("今日の運勢は「" + results[random] + "」です。");
  }
}

問題 2 難易度 ★★★

① 西暦を入力すると、その年の干支を表示するプログラムを作成してください。
(参考)西暦 0 年は申年、西暦 1 年は酉年です。
(十二支)”子”, “丑”, “寅”, “卯”, “辰”, “巳”, “午”, “未”, “申”, “酉”, “戌”, “亥”。

実行例

干支を知りたい年を、西暦で入力してください。
2019
西暦 2019 年は、亥年です。

問題 2 解答

正解は、、、
public class Main_0402 {
  public static void main(String[] args) {
  String[] eto = {
    "", "", "", "", "", "", "", "", "", "", "", "" };
    System.out.println("干支を知りたい年を、西暦で入力してください。");
    int year = new java.util.Scanner(System.in).nextInt();
    String result = eto[(year + 8) % eto.length];
    System.out.println("西暦" + year + "年は、" + result + "年です。");
  }
}

配列と for 文の組み合わせ

問題 3 難易度 ★★

① 文字列配列{“black”,”white”,”red”,”blue”,”green”,”yellow”}の中に、
キーボードから入力した文字列が含まれているかどうかを調べるプログラムを作成してください。

実行例 1

配列の中に存在するか調べたい文字列を入力してください。
red
red は、配列の中に存在しています。

実行例 2

配列の中に存在するか調べたい文字列を入力してください。
gold
gold は、配列の中に存在していません。

問題 3 解答

正解は、、、
public class Main_0403 {
  public static void main(String[] args) {
    String[] colors = {
      "black", "white", "red", "blue", "green", "yellow" };
      
    System.out.println("配列の中に存在するか調べたい文字列を入力してください。");
    String str = new java.util.Scanner(System.in).nextLine();
    String msg = "存在していません。";
    
    for (int i = 0; i < colors.length; i++) {
      if (str.equals(colors[i])) {
          msg = "存在しています。";
      }
    }
    System.out.println(str + "は、配列の中に、" + msg);
  }
}

配列応用

問題 4 難易度 ★★★

① 1~12 の範囲で月を入力すると、日本での季節を表示するプログラムを以下の配列を用いて作成してください。
(1,2,12 月は冬、3,4,5 月は春、6,7,8 月は夏、9,10,11 月は秋、を表示)。

String[] seasons = { “冬”, “春”, “夏”, “秋” };

実行例

1~12 の範囲で月を入力してください。
3
日本の 3 月は、春です。

問題 4 解答

正解は、、、
public class Main_0404 {
  public static void main(String[] args) {
    String[] seasons = { "", "", "", "" };
    System.out.println("1~12 の範囲で月を入力してください。");
    int month = new java.util.Scanner(System.in).nextInt();
    String result = seasons[month / 3 % 4];
    System.out.println("日本の" + month + "月は、" + result + "です。");
  }
}

Java練習問題 第7回でも引き続き「配列」から出題します。

(Visited 291 times, 1 visits today)
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

コメント

コメントする

目次