-1

Code:

    int letter1 = 65 + (int) (Math.random() * (90 - 65));
    int letter2 = 65 + (int) (Math.random() * (90 - 65));
    int letter3 = 65 + (int) (Math.random() * (90 - 65));

    int number1 = (int) (Math.random() * 10);
    int number2 = (int) (Math.random() * 10);
    int number3 = (int) (Math.random() * 10);
    int number4 = (int) (Math.random() * 10);

    System.out.println("" + (char)letter1 + (char)letter2 + (char)letter3 + "-"
                                    + number1 + number2 + number3 + number4);

This is the lines of code to generate random license plate, and I have a question on why I need to add "" at the beginning of the System.out.println argument. When I don't put quotation marks at the beginning of the arugments, the letter variables don't change to char type and end up returning integer values whereas when they are there, the variables change into char type and return random alphabets.

I don't quite get why I need the quotation marks to return the char type.

  • 2
    `+` is *addition* when both operands are *numeric* and `char` is considered as numeric type. `+` becomes concatenation when at least one of operands is String. Also `+` is evaluated from left to right, so `x + y + z` is same as `(x + y) + z`. – Pshemo Jul 15 '22 at 02:33
  • Possibly related: [Why Char won't print, and counter exceeded my loop;](https://stackoverflow.com/q/56104516), [Java printing a string containing multiple integers](https://stackoverflow.com/q/18041996), [What is the precedence of the + (plus) operator in Java?](https://stackoverflow.com/q/19995956) – Pshemo Jul 15 '22 at 02:43

1 Answers1

1

I would start by replacing the magic numbers you have here with their literal char constant equivalents. Next, use formatted output and you don't have to cast them back to char (although it does make the code easier to reason about). Like,

int letter1 = (int) ('A' + (Math.random() * ('Z' - 'A')));
int letter2 = (int) ('A' + (Math.random() * ('Z' - 'A')));
int letter3 = (int) ('A' + (Math.random() * ('Z' - 'A')));

int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
int number3 = (int) (Math.random() * 10);
int number4 = (int) (Math.random() * 10);
System.out.printf("%c%c%c-%d%d%d%d%n", letter1, letter2, letter3, 
        number1, number2, number3, number4);

Using "" causes String concatenation at the beginning. Remember char is a 16-bit integer type.

Also, you could replace the four digit random number routine with

int number1 = (int) (Math.random() * 10000);
System.out.printf("%c%c%c-%04d%n", letter1, letter2, letter3, number1);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249