Home>

Use import java.util.Random;to put a random number in an int type array once, cast it to a char type array, and repeat it 4 times to output a 4-digit random number.

Cast conversion is not possible
Corresponding source code
import java.util.Random;
public class Test01 {
    public static void main (String [] args) {
        Random ran = new Random ();
        for (int i = 0;i<4;i ++) {
            int [] Number = {ran.nextInt (10)};
            char [] suzi = {(char) Number};
For (int j = 0;j<char.length;j ++) {
                                System.out.print (char [j]);
                        }
        }
    }
}
  • Answer # 1

    Even if you don't bother to take such a troublesome method, you can get almost the same result by generating one random number from 0 to 9999 (although it is necessary to pad with 0 when there are not enough digits).

  • Answer # 2

    In the first place, there is no method that can convert an int array to a char array in one shot.
    Even if you get random numbers one by one, the process of creating an int array is completely useless.
    It would be easier to convert a single digit value of int to char and put it in an array in order.

    public static void main (String [] args) {
        Random ran = new Random ();
        char [] suzi = new char [4];
        for (int i = 0;i<4;i ++) {
            suzi [i] = (char) (ran.nextInt (10) + 48);
        }
        System.out.print (suzi);
    }

    And as a bonus, it is a method proposed by maisumakun to get a 4-digit number with a random number and fill it with 0s.
    I finally converted it to a char array by saying that I want it as a char array.

    public static void main (String [] args) {
        Random ran = new Random ();
        int num = ran.nextInt (10000);
        char [] suzi = (String.format ("% 04d", num)). toCharArray ();
        System.out.print (suzi);
    }