-1

I'm new to java and was viewing a tutorial and saw nextInt, the guy said that it was supposed to give me a number between -5 and 5 but i have two problems :

(r.nextInt(5 - -5) + -5)

1)In what order does it operate

2)The explanation that i found says that it doesn't accept negatives then why is it supposed to allow me to give me -5?

Thanks a lot.

Darkly
  • 385
  • 1
  • 3
  • 18

2 Answers2

1

What your code will do is generate a random integer between 0 and the specified value, and will then subtract 5 from the generated integer.

maldahleh
  • 313
  • 3
  • 18
1

The answer is unary negative and subtration. Usually, that's written as +. Like

(r.nextInt(5 + 5) + -5)

which is

(r.nextInt(10) - 5)

I assume this is for a Random, in which case it returns [0,10). Which if you subtract 5, is [-5,5).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Oh i get it now so the -5 substracts from both minimum and the maximum not just from the maximum, thanks! – Darkly Dec 04 '15 at 02:10
  • @Darkly It subtracts from the single value which is in the minimum to maximum range. Draw a number line from 0 to n, then move the origin point (*minimum*) left or right... to preserve the original line length you must move the end point (*maximum*) left or right by the same distance. – Elliott Frisch Dec 04 '15 at 02:13