Java 创建一个随机的 4 位数字,并将其存储为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22238458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:30:15  来源:igfitidea点击:

Creating a random 4 digit number, and storing it to a string

javaandroid

提问by user3247335

I'm trying to create a method which generates a 4 digit integer and stores it in a string. The 4 digit integer must lie between 1000 and below 10000. Then the value must be stored to PINString. Heres what I have so far. I get the error Cannot invoke toString(String) on the primitive type int. How can I fix it?

我正在尝试创建一个生成 4 位整数并将其存储在字符串中的方法。4 位整数必须介于 1000 和 10000 以下。然后该值必须存储到PINString. 这是我到目前为止所拥有的。我收到错误Cannot invoke toString(String) on the primitive type int。我该如何解决?

   public void generatePIN() 
   {

        //generate a 4 digit integer 1000 <10000
        int randomPIN = (int)(Math.random()*9000)+1000;

        //Store integer in a string
        randomPIN.toString(PINString);

    }

采纳答案by mikejonesguy

You want to use PINString = String.valueOf(randomPIN);

你想用 PINString = String.valueOf(randomPIN);

回答by Alexis C.

randomPINis a primitive datatype.

randomPIN是原始数据类型。

If you want to store the integer value in a String, use String.valueOf:

如果要将整数值存储在 a 中String,请使用String.valueOf

String pin = String.valueOf(randomPIN);

回答by peter.petrov

Try this approach. The x is just the first digit. It is from 1 to 9.
Then you append it to another number which has at most 3 digits.

试试这个方法。x 只是第一个数字。它是从 1 到 9。
然后将它附加到另一个最多 3 位数的数字上。

public String generatePIN() 
{   
    int x = (int)(Math.random() * 9);
    x = x + 1;
    String randomPIN = (x + "") + ( ((int)(Math.random()*1000)) + "" );
    return randomPIN;
}

回答by Zied R.

Use a string to store the value:

使用字符串存储值:

   String PINString= String.valueOf(randomPIN);

回答by Sharp Edge

Make a String variable, concat the generated int value in it:

创建一个 String 变量,将生成的 int 值连接到其中:

int randomPIN = (int)(Math.random()*9000)+1000;
String val = ""+randomPIN;

OR even more simple

或者更简单

String val = ""+((int)(Math.random()*9000)+1000);

Can't get any more simple than this ;)

没有比这更简单的了 ;)