Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidアプリに指定範囲の乱数を生成する方法をわかりやすく解説

この記事では、Kotlinを使用してAndroidアプリで指定した範囲内の乱数を生成する方法を、実際のコード例とともにステップごとに解説します。最小値と最大値をユーザーに入力させ、その間のランダムな整数を表示するシンプルなアプリを作成しましょう。

完成イメージ

画面には「Minimum(最小値)」と「Maximum(最大値)」を入力する2つのテキストボックスと、「GENERATE」ボタンを配置します。ボタンをタップすると、入力された範囲内からランダムな数値が1つ選ばれて画面に表示される仕組みです。

手順1:新規プロジェクトの作成

まずAndroid Studioを起動し、メニューから[File] → [New Project]を選択して新しいプロジェクトを作成します。必要な項目(プロジェクト名、パッケージ名、保存先など)を入力して「Empty Activity」テンプレートでプロジェクトを作成してください。

手順2:レイアウトファイル(activity_main.xml)の編集

次に、res/layout/activity_main.xmlに以下のコードを追加します。TextView・EditText×2・ButtonをRelativeLayoutで配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/editTextMin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text"
        android:layout_centerInParent="true"
        android:layout_marginTop="50dp"
        android:ems="10"
        android:hint="Minimum"
        android:inputType="number" />

    <EditText
        android:id="@+id/editTextMax"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextMin"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Maximum"
        android:inputType="number" />

    <Button
        android:id="@+id/btn_generate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextMax"
        android:layout_centerInParent="true"
        android:layout_marginTop="5dp"
        android:text="GENERATE" />

    <TextView
        android:id="@+id/textViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_generate"
        android:layout_centerInParent="true"
        android:layout_marginTop="10dp"
        android:text=""
        android:textColor="@android:color/black"
        android:textSize="24sp"
        android:textStyle="bold" />

</RelativeLayout>

手順3:MainActivity.ktの実装

src/MainActivity.ktに以下のコードを記述します。ポイントは乱数生成の部分です。random.nextInt(max - min + 1) + minという式により、「min以上max以下」の整数を取得できます。nextInt()は0〜引数未満の値を返すため、範囲の調整にはこの計算式が定番です。

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*

class MainActivity : AppCompatActivity() {

    lateinit var editTextMin: EditText
    lateinit var editTextMax: EditText
    lateinit var button: Button
    lateinit var textView: TextView

    private var min = 0
    private var max: Int = 0
    private var output: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val random = Random()
        editTextMin = findViewById(R.id.editTextMin)
        editTextMax = findViewById(R.id.editTextMax)
        button = findViewById(R.id.btn_generate)
        textView = findViewById(R.id.textViewResult)

        button.setOnClickListener {
            val tempMin: String = editTextMin.text.toString()
            val tempMax: String = editTextMax.text.toString()

            if (tempMin != "" && tempMax != "") {
                min = tempMin.toInt()
                max = tempMax.toInt()

                if (max > min) {
                    output = random.nextInt(max - min + 1) + min
                    textView.text = "" + output
                }
            }
        }
    }
}

コードの解説

  • 入力チェック: 両方のEditTextが空でない場合のみ処理を実行し、不正な入力によるクラッシュを防いでいます。
  • 範囲の検証: 最大値が最小値より大きい場合のみ乱数を生成するようにしています。
  • 乱数の生成: nextInt(max - min + 1)で0〜(max−min)までの値を取得し、minを加算することで目的の範囲に変換しています。

手順4:AndroidManifest.xmlの確認

androidManifest.xmlには以下のようにMainActivityがランチャーアクティビティとして登録されていることを確認してください。このサンプルでは特別なパーミッションは不要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

アプリの実行

それではアプリを実行してみましょう。実機のAndroidスマートフォンをパソコンにUSB接続している前提で進めます。Android Studioでプロジェクト内の任意のアクティビティファイルを開き、ツールバーの実行(Run)アイコンをクリックしてください。デバイス選択ダイアログが表示されたら、接続したスマートフォンを選択します。

アプリが起動したら、最小値と最大値を入力して「GENERATE」ボタンをタップします。指定した範囲内のランダムな数値が画面に表示されれば成功です。

KotlinでAndroidアプリに指定範囲の乱数を生成する方法をわかりやすく解説

まとめ

KotlinではRandomクラスのnextInt()メソッドを活用することで、簡単に指定範囲の乱数を生成できます。また、Kotlin 1.3以降では標準ライブラリのkotlin.random.Random.nextInt(min, max + 1)を使う方法もあり、より簡潔に記述できるので、あわせて覚えておくと便利です。サイコロアプリやくじ引きアプリなど、さまざまな場面で応用できるテクニックなので、ぜひマスターしてください。

  1. Android SQLiteでrandom()を使う方法を初心者向けに解説【サンプルコード付き】

    はじめに:AndroidにおけるSQLiteデータベースとは本題に入る前に、AndroidにおけるSQLiteデータベースについて簡単に確認しておきましょう。SQLiteはオープンソースのSQLデータベースで、データをデバイス上のテキストファイルとして保存します。Androidには標準でSQLiteデータベースの実装が組み込まれており、リレーショナルデータベースの機能をすべてサポートしています。JDBCやODBCのような接続設定を確立する必要はなく、手軽にデータベースへアクセスできるのが大きな特徴です。この記事では、SQLiteのrandom()関数を使って、テーブル内のレコードをランダムな順

  2. Androidで指定した範囲の乱数を生成する方法【初心者向けサンプルコード付き】

    この記事では、Androidアプリで指定した範囲(最小値〜最大値)の中からランダムな数値を生成する方法を、実際に動作するサンプルコードとともに解説します。ユーザーが入力した最小値と最大値をもとに、ボタンをタップすると乱数が画面に表示されるシンプルなアプリを作成していきます。 乱数生成の基本的な仕組み Java標準のjava.util.Randomクラスを利用すると、簡単に乱数を生成できます。任意の範囲内の乱数を取得するには、次の式を使います。 output = r.nextInt((max - min) + 1) + min; nextInt(n)メソッドは「0以上 n 未満」の整数を返します