1
0

More than 3 years have passed since last update.

[Java基礎④] while処理/繰り返し回数もランダムにする Math.random

Last updated at Posted at 2021-09-02

初めに

Java学習開始4日目です。
今回はwhile処理を学習しました。

While処理の基本形

コード
public class Main {
    public static void main(String[] args) {
        int i = 0;    // カウンタ変数の初期化
        while (i <= 5) {
            System.out.println(i);    // 繰り返し処理
            i += 1;    // カウンタ変数の更新
        }
    }
}

繰り返しの回数をランダムにする

public class Main {
    public static void main(String[] args) {
        int hp = 30;
        int hit;    // カウンタ変数の初期化
        while (hp > 0) {
            hit = (int)(Math.random()*5 + 5);
            System.out.println(hit + "のダメージを与えた");    // 繰り返し処理
            hp -= hit;    // カウンタ変数の更新
        }
            System.out.println("敵を倒した");
    }
}

まず、int hit;の値は、hit = (int)(Math.random()*5 + 5);
でランダムに出力されます。
hp -= hit;でhpの値もランダムになるため、
繰り返しの回数もランダムになります。

1
0
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
1
0