Create a random 4-digit number and save it in a string

I am trying to create a method that generates a 4-digit integer and stores it in a string. A 4-digit integer must be between 1000 and below 10000. Then the value must be stored in the PINString . Here is what I still have. I get Cannot invoke toString(String) on the primitive type int error Cannot invoke toString(String) on the primitive type int . How can i fix this?

  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); } 
+7
java android
source share
5 answers

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

+10
source share

Create a String variable, add the generated int value to it:

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

OR even simpler

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

It could not be easier than that;)

+7
source share

randomPIN is a primitive data type.

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

 String pin = String.valueOf(randomPIN); 
+1
source share

Try this approach. X is only the first digit. This is from 1 to 9.
Then you add it to another number that has no more than 3 digits.

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

Use the string to save the value:

  String PINString= String.valueOf(randomPIN); 
0
source share

All Articles