Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách tạo số ngẫu nhiên trong khoảng cho trước trên Android

Giới thiệu

Bài viết này hướng dẫn tạo ứng dụng sinh số ngẫu nhiên trong khoảng [min, max] do người dùng nhập, sử dụng lớp java.util.Random và phương thức nextInt().

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và tạo dự án.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?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">

    <EditText
        android:id="@+id/et_min"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Giá trị nhỏ nhất"
        android:inputType="number" />

    <EditText
        android:id="@+id/et_max"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_min"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Giá trị lớn nhất"
        android:inputType="number" />

    <Button
        android:id="@+id/btn_generate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_max"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TẠO SỐ" />

    <TextView
        android:id="@+id/tv_output"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_generate"
        android:layout_centerHorizontal="true"
        android:textSize="30sp"
        android:hint="Kết quả" />

</RelativeLayout>

Bước 3: Viết code logic (src/MainActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    EditText etMin, etMax;
    Button btnGenerate;
    TextView tvOutput;
    Random random;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        random = new Random();
        etMin = findViewById(R.id.et_min);
        etMax = findViewById(R.id.et_max);
        btnGenerate = findViewById(R.id.btn_generate);
        tvOutput = findViewById(R.id.tv_output);

        btnGenerate.setOnClickListener(v -> {
            String minStr = etMin.getText().toString().trim();
            String maxStr = etMax.getText().toString().trim();

            if (minStr.isEmpty() || maxStr.isEmpty()) {
                tvOutput.setText("Vui lòng nhập đủ 2 giá trị");
                return;
            }

            try {
                int min = Integer.parseInt(minStr);
                int max = Integer.parseInt(maxStr);

                if (max <= min) {
                    tvOutput.setText("Max phải lớn hơn Min");
                    return;
                }

                // Công thức: nextInt((max - min) + 1) + min
                int result = random.nextInt((max - min) + 1) + min;
                tvOutput.setText(String.valueOf(result));
            } catch (NumberFormatException e) {
                tvOutput.setText("Giá trị không hợp lệ");
            }
        });
    }
}

Bước 4: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập giá trị Min (ví dụ 10) và Max (ví dụ 100), nhấn "TẠO SỐ". Kết quả hiển thị số ngẫu nhiên trong khoảng [10, 100].

Giải thích công thức

random.nextInt((max - min) + 1) + min
  • nextInt(n) trả về số ngẫu nhiên từ 0 đến n-1
  • (max - min) + 1 là tổng số lượng giá trị có thể có trong khoảng
  • Cộng min để dịch dải giá trị từ [0, n-1] sang [min, max]

Các cách khác tạo số ngẫu nhiên

  • ThreadLocalRandom (Java 7+): ThreadLocalRandom.current().nextInt(min, max + 1) - hiệu suất tốt hơn trong đa luồng
  • SecureRandom: Dùng cho mục đích bảo mật/mã hóa
  • Math.random(): Trả về double [0,1), công thức: (int)(Math.random() * (max - min + 1)) + min
  • Kotlin: (min..max).random() hoặc Random.nextInt(min, max + 1)