LoginSignup
2
1

More than 5 years have passed since last update.

Java 乱数&for文&出力

Last updated at Posted at 2016-09-16

【問題】

1から10までの乱数を発生させ、その数を表示した後forループを用いてその数だけ■マークを表示するプログラムを作りなさい。

【回答】

// Randomというクラスに属している乱数発生関数(nextInt)を
// 使いたいため、ランダムクラスをインポートします
import java.util.Random;

public class Study {

    public static void main(String[] args) {
        // Randomクラスのインスタンス化(初期化)
        Random rand = new Random();

        // 1~10までの乱数を発生
        // nextInt(10)は0~9までの数字を発生させる
        // そのためプラス1をして1~10までの数字をrandomNum変数に代入している
        int randomNum = rand.nextInt(10) + 1;
        // ランダムに発生した数を表示
        System.out.println(randomNum);

        // for文で使用する変数の宣言
        int i;
        // 1~randomNum以下まで繰り返します
        for (i = 1; i <= randomNum; i++) {
            // ■マークの表示
            // 横一列に並べたいため改行をしないprintを使用
            System.out.print("■");
        }
    }
}

【参考サイト】

乱数の作成

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1