简体   繁体   English

如何在Android / Java中根据特定的起始/结束号正确生成随机整数?

[英]How do I properly generate a random integer based on a specific start/end number in Android/Java?

I'm trying to create an Android app that takes in a user-inputted "from" number and "to" number (a range) and then generates a random integer from within that range. 我正在尝试创建一个Android应用,该应用接受用户输入的“从”数字和“至”数字(一个范围),然后从该范围内生成一个随机整数。 I'm using 2 EditTexts with the number inputType so that the user can input their unique values, and then I tried to work with the EditTexts in the corresponding Java files (both files are attached below). 我正在使用2个EditText,其number inputType以便用户可以输入其唯一值,然后我尝试在相应的Java文件(两个文件均附在下面)中使用EditText。

I looked here and here and here . 我看着这里这里这里

However, Android Studio can build (compile) my app, but when I run the app in the emulator (which has been working before I added this logic), it refuses to even load the Activity and instead says "Unfortunately, [App] has stopped." 但是,Android Studio可以构建(编译)我的应用程序,但是当我在模拟器中运行该应用程序(在添加此逻辑之前已经运行)时,它甚至拒绝加载Activity,而是说“不幸的是,[App]已停止“。 I think it has something to do with leaving some parts of the "addTextChangedListener" code empty, but I don't know what exactly to put there (I took it from the examples I linked to above). 我认为这与将“ addTextChangedListener”代码的某些部分保留为空白有关,但是我不知道确切该放在哪里(我从上面链接的示例中获取了它)。

What on Earth am I doing wrong, and how can I fix what I've done to make the code function properly? 我到底在做什么错,我该如何解决使代码正常运行的问题? Or maybe there is an easier way that I haven't discovered yet... 也许还有一种我还没有发现的简单方法...

Thanks! 谢谢!

Here is my XML activity code: 这是我的XML活动代码:

    <EditText
        android:id="@+id/editText_from"
        android:ems="10"
        android:gravity="center"
        android:hint="@string/string_from"
        android:importantForAutofill="no"
        android:inputType="number" />

    <EditText
        android:id="@+id/editText_to"
        android:ems="10"
        android:gravity="center"
        android:hint="@string/string_to"
        android:importantForAutofill="no"
        android:inputType="number" />

Here is my Java code: 这是我的Java代码:

package com.example.appname;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class NumberActivity extends AppCompatActivity {
    private EditText editTextFrom;
    private EditText editTextTo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number);
        editTextFrom = (EditText) findViewById(R.id.editText_from);
        editTextTo = (EditText) findViewById(R.id.editText_to);
        editTextFrom.setText(editTextFrom.getEditableText());
        editTextTo.setText(editTextTo.getEditableText());
        final int fromValue = 0;
        editTextFrom.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // What do I put here?
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // What do I put here?
            }

            @Override
            public void afterTextChanged(Editable s) {
                editTextFrom.setText(fromValue);
            }
        });
        final int toValue = 0;
        editTextTo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // What do I put here?
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // What do I put here?
            }

            @Override
            public void afterTextChanged(Editable s) {
                editTextFrom.setText(toValue);
            }
        });
        int randomNum = ThreadLocalRandom.current().nextInt(fromValue, toValue);
        return;
    }
}

So, you need to generate a random number between a certain range. 因此,您需要在一定范围之间生成一个随机数。 You have a button, which when clicked, you need that random number to be generated. 您有一个按钮,单击该按钮时需要生成该随机数。 So what does that mean? 那是什么意思呢? It means you don't need to add editText.addTextChangedListener to listen continuously for the text changes. 这意味着您无需添加editText.addTextChangedListener即可连续侦听文本更改。

Step 1. Create a method called generateRandomNumber. 步骤1.创建一个名为generateRandomNumber的方法。

private int generateRandomNumberBetweenRange(int from, int to){
    return ThreadLocalRandom.current().nextInt(fromValue, toValue);
}

Step 2: Set onClickListener to the button that you have in your XML, and in the onClick of this button, get the values from EditText and pass those values to the function created in step 1. 步骤2:将onClickListener设置为XML中具有的按钮,然后在此按钮的onClick中,从EditText获取值,并将这些值传递给在步骤1中创建的函数。

button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              int fromValue = Integer.parseInt(fromValueEditText.getText().toString());
              int toValue = Integer.parseInt(toValueEditText.getText().toString());
              int randomNumber = generateRandomNumberBetweenRange(fromValue, toValue);
              //Your random Number is generated, you can now do whatever you want with it.
              }
          });

I am not sure if this is your problem exactly but it seems you have fromValue and toValue both set as final which means they cannot change after they were both set to 0. That means your int randomNum = ThreadLocalRandom.current().nextInt(fromValue, toValue); 我不知道如果这是你的问题究竟但似乎你有fromValuetoValue都设置为final这意味着它们都设置为0后,他们无法改变这意味着您的int randomNum = ThreadLocalRandom.current().nextInt(fromValue, toValue); is always attempting to call nextInt(0,0) which according to the javadocs here will throw an IllegalArgumentException . 一直尝试调用nextInt(0,0) ,根据这里的javadocs 它将抛出IllegalArgumentException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM