8

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?

   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);

    }
Blue Ice
  • 7,888
  • 6
  • 32
  • 52
user3247335
  • 181
  • 2
  • 5
  • 16
  • Why do you want it higher than 1000. I think that 0050 is a valid number (though looks strange). – AlikElzin-kilaka Jun 09 '14 at 10:35
  • obviously not an exact duplicate but it's the same problem with the same solution...so. – Ryan Haining Jun 10 '14 at 04:34
  • For those seeking to generate OTP Pins that could have values like 0004, 0032 or 0516. Here is the code. `Random random = new Random(); String generatePin = String.format("%04d", random.nextInt(10000)); System.out.println(generatePin);` – KNDheeraj Sep 30 '18 at 16:32
  • Here is another way. `Random random = new Random(); String generatePin = String.format("%04d", random.nextInt(10000000) % 10000); System.out.println(generatePin);` – KNDheeraj Sep 30 '18 at 16:33

5 Answers5

11

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

mikejonesguy
  • 9,779
  • 2
  • 35
  • 49
10

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

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 ;)

Sharp Edge
  • 4,144
  • 2
  • 27
  • 41
2

randomPIN is a primitive datatype.

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

String pin = String.valueOf(randomPIN);
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
1

Use a string to store the value:

   String PINString= String.valueOf(randomPIN);
Zied R.
  • 4,964
  • 2
  • 36
  • 67
0

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.

public String generatePIN() 
{   
    int x = (int)(Math.random() * 9);
    x = x + 1;
    String randomPIN = (x + "") + ( ((int)(Math.random()*1000)) + "" );
    return randomPIN;
}
DoronK
  • 4,837
  • 2
  • 32
  • 37
peter.petrov
  • 38,363
  • 16
  • 94
  • 159