Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีสุ่มตัวเลขในช่วงที่กำหนดใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการสุ่มตัวเลขในช่วงที่ผู้ใช้กำหนด (Minimum - Maximum) โดยใช้คลาส Random ของ Java

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: ออกแบบ Layout (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="ค่าต่ำสุด (Minimum)"
        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="ค่าสูงสุด (Maximum)"
        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="สุ่มเลข" />

    <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="ผลลัพธ์"
        android:text="" />

</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity (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 android.widget.Toast;
import java.util.Random;

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

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

        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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String minStr = etMin.getText().toString().trim();
                String maxStr = etMax.getText().toString().trim();

                if (minStr.isEmpty() || maxStr.isEmpty()) {
                    Toast.makeText(MainActivity.this, 
                        "กรุณากรอกค่าต่ำสุดและสูงสุด", Toast.LENGTH_SHORT).show();
                    return;
                }

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

                if (max <= min) {
                    Toast.makeText(MainActivity.this, 
                        "ค่าสูงสุดต้องมากกว่าค่าต่ำสุด", Toast.LENGTH_SHORT).show();
                    return;
                }

                // สุ่มเลขในช่วง [min, max] รวมทั้งสองข้าง
                int result = random.nextInt((max - min) + 1) + min;
                tvOutput.setText(String.valueOf(result));
            }
        });
    }
}

ขั้นตอนที่ 4: 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>

การทำงานของ nextInt()

// สุ่ม 0 ถึง n-1
random.nextInt(n)

// สุ่มในช่วง [min, max] รวมทั้งสองข้าง
int result = random.nextInt((max - min) + 1) + min;

// ตัวอย่าง: สุ่ม 1-6 (เต๋า)
int dice = random.nextInt(6) + 1; // 1-6

// ตัวอย่าง: สุ่ม 10-20
int num = random.nextInt(11) + 10; // 10-20

คลาส ThreadLocalRandom (Java 7+) - ทางเลือกที่ดีกว่าสำหรับ Multi-thread

import java.util.concurrent.ThreadLocalRandom;

// สุ่ม int ในช่วง [min, max]
int result = ThreadLocalRandom.current().nextInt(min, max + 1);

// สุ่ม double ในช่วง [min, max)
double result = ThreadLocalRandom.current().nextDouble(min, max);

การทดสอบ

รันแอป กรอกค่าต่ำสุด 1 ค่าสูงสุด 100 กด "สุ่มเลข" จะได้ตัวเลขสุ่มในช่วง 1-100

วิธีสุ่มตัวเลขในช่วงที่กำหนดใน Android วิธีสุ่มตัวเลขในช่วงที่กำหนดใน Android