public static void main(String[] args) { Scanner a = new Scanner(System.in); int x = 0; int y, c, b; y = a.nextInt(); c = a.nextInt(); Random r = new Random(System.currentTimeMillis()); for (x = 0; x < 20; x++) { b = r.nextInt(c) + y; System.out.println(b); } } 

My code displays random numbers without a range, I can not understand what is wrong, and the values ​​can be negative

  • Do not use new Random(System.currentTimeMillis()) . Use just new Random() . - Tagir Valeev

2 answers 2

Try this:

 public static void main(String[] args) { Scanner a = new Scanner(System.in); int result = 0; int y = a.nextInt(); int c = a.nextInt(); int diff = c - y; Random r = new Random(); for (int x = 0; x < 20; x++) { result = r.nextInt(diff) + y; System.out.println(result); } } 

The result here is not including the number c . If you want to output it, then you need to add 1 to the diff variable, like this:

 int diff = c - y + 1; 
     public static void main(String[] args) { Scanner a = new Scanner(System.in); int x = 0; int y, c, b; y = a.nextInt(); c = a.nextInt(); Random r = new Random(); for (x = 0; x < 20; x++) { System.out.println(r.nextInt(20)); } } 
    • Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky