-2

I'm trying to make a random array list in range [-250, 250] and print the numbers, then the sum just once, at the end of the code for all of the numbers below. here is my code:

public class Main {
  public static void main(String[] args) {
      Random rand = new Random();
      int max = 250;
      int min = -250;
      for  ( int  i = 1 ; i <= 50 ; i ++){
          int rez = min + rand.nextInt(max) * 2;
          System.out.println("The number is : " + i);
          int sum = rez + rez;
          System.out.println("The sum is: " + rez);
      } 

This is the code so far. It works. But I want to print the sum just once, at the end of the code for all of the numbers above. My code so far prints the sum individually.

I also tried it like this


    for  ( int  i = 1 ; i <= 50 ; i ++) {
            int rez = min + rand.nextInt(max) * 2;
            System.out.println("The number is : " + i);
            int sum = rez + rez;
        }
            System.out.println("The sum is: " + rez); 

but it gives me this error "Cannot resolve symbol 'rez'" Can someone please tell me what I did wrong?

  • 3
    Your try to access the variable when it isn't in scope. Declare the variable before the loop to give it the right scope. You also for some reason try to print `rez` instead of `sum`, and to calculate the sum you would need to do `sum = sum + rez;`. – OH GOD SPIDERS Sep 22 '22 at 11:51

2 Answers2

0

You are declaring the variable inside the loop, so cannot be seen outside it.

scope in java

icrovett
  • 435
  • 7
  • 21
0

You get the error because you created the variable rez in the for loop, so it is only available there. You should create it before the for loop. See here

 int rez = 0;
int sum = 0;
for  ( int  i = 1 ; i <= 50 ; i ++) {
            rez = 0;
            rez = min + rand.nextInt(max) * 2;
            System.out.println("The number is : " + i);
            sum = rez + rez;
}
System.out.println("The sum is: " + rez);
Der Dude
  • 11
  • 2