0

What is the use of plus "+" symbol in code?

Eg: (char) (myRandom.nextInt(26) **+** 'A')

2

In this case, the + is moving to the next char in the alphabet from where you are.

The random part doesn't help explain, so this snippet may help.

char x = (char)(1 + 'A'); // returns B.  Pos 1 + A (1) gives 2 => B
x = (char)(2 + 'A'); // returns C.  Pos 2 + A (1) gives 3 => C
x = (char)(3 + 'A'); // returns D.  Pos 3 + A (1) gives 6 => D
x = (char)(1 + 'A'); // returns B.  Pos 1 + A (1) gives 2 => B
x = (char)(2 + 'B'); // returns D.  Pos 2 + B (2) gives 4 => D
x = (char)(3 + 'C'); // returns F.  Pos 3 + C (3) gives 6 => F

Your random statement is seeded with 26. So nextInt(26) will return a random number between 0 and 26. Whatever is returned by that is that moved on one position by the + 'A' part.

  • There is a mistake in your comments to the code. 'A' is not coded with 1, otherwise you would not need to use 1+'A', you would just use 2. The sense of using "number+'A'" is that you are not aware of what number "A" is encoded with. So "1+A" will not give you 2. – Alexey R. Oct 16 '17 at 9:16
  • Hi, you've take 'gives' too literally. I was just showing how (1+'A') would return 'B'. – Chris Adams Oct 16 '17 at 9:19
0

This particular line means that you take a random shift from 'A'. Say if

myRandom.nextInt(26) == 1

then you will get 'B'

Not the answer you're looking for? Browse other questions tagged or ask your own question.