Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 Android에서 지정된 범위의 난수를 생성하는 방법

Kotlin으로 Android에서 지정된 범위의 난수 생성하기

이 튜토리얼에서는 Kotlin을 사용해 Android 앱에서 사용자가 지정한 범위 내의 난수를 생성하는 방법을 단계별로 알아봅니다. 최솟값과 최댓값을 입력한 뒤 버튼을 누르면 해당 범위 사이의 무작위 숫자가 화면에 표시되는 간단한 예제입니다.

1단계: 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택하여 새 프로젝트를 만듭니다. 프로젝트 생성에 필요한 모든 세부 정보를 입력한 후 진행하세요.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이 레이아웃에는 최솟값과 최댓값을 입력받는 두 개의 EditText, 난수 생성 버튼, 그리고 결과를 표시할 TextView가 포함되어 있습니다.

<?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" />
   <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" />
   <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" />
   <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:hint="Output"
      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 부분으로, nextInt()는 0부터 인자 값 미만까지의 수를 반환하므로 여기에 최솟값을 더하면 min 이상 max 이하의 난수를 얻을 수 있습니다.

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
            }
         }
      }
   }
}

코드가 동작하는 흐름은 다음과 같습니다. 먼저 두 입력 필드의 값이 비어 있는지 검사하고, 값이 있다면 정수로 변환합니다. 이후 최댓값이 최솟값보다 큰 경우에만 난수를 생성하여 결과 TextView에 출력합니다. 잘못된 입력으로 인한 비정상 종료를 방지하기 위한 기본적인 유효성 검사도 포함되어 있습니다.

4단계: AndroidManifest.xml 설정

androidManifest.xml에 아래 코드가 올바르게 작성되어 있는지 확인합니다. 본 예제에는 특별한 권한이 필요하지 않습니다.

<?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 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘Kotlin으로 Android에서 지정된 범위의 난수를 생성하는 방법을 클릭하세요. 실행 대상 목록에서 자신의 모바일 기기를 선택하면, 해당 기기 화면에 앱이 실행됩니다.

앱이 실행되면 최솟값(Minimum)과 최댓값(Maximum)을 입력하고 GENERATE 버튼을 누릅니다. 그러면 두 값 사이의 무작위 숫자가 화면에 표시됩니다. 버튼을 누를 때마다 새로운 난수가 생성되는 것을 확인할 수 있습니다.

Kotlin으로 Android에서 지정된 범위의 난수를 생성하는 방법