Home > Net >  Do if statements have their own scope?
Do if statements have their own scope?

Time:11-15

I was doing a java exercise the other day and in the exercise we had to get input from the user and then figure out what the max value was and what the average was. We then had to print out those values. Values could only be positive integers and when the user enters a negative integer the program should stop taking in values and not account for that negative integer into the average calculation. My problem was I couldn't figure out a way to compare the current integer entered by the user to the max value.

I just made it's own if statement for it and I was expecting a compile error that the max variable didn't have a value or something like that, but the code worked just fine. So my question is do if statements have their own scope or not? What even has scope in programming and what doesn't.

import java.util.Scanner; 

public class LabProgram {
   public static void main(String[] args) {
      //Create Scanner.
      Scanner inp = new Scanner(System.in);
  
      //Declare and initialize variables.
      double average;
      int sum = 0;
      int num;
      int counter = 0;
      int max = 0;
  
      //Process.
      do
      {
         num = inp.nextInt();
         sum  = num;
         if(num > max)
         {
            max = num;
         }
         if(num < 0)
         {
        
            sum -= num;
            System.out.print(max);
            average = sum/(double)counter;
            System.out.printf(" %.2f\n", average);
         }
           counter;
      }while(num >= 0);
     
   }
}

CodePudding user response:

Do if statements have their own scope?

No, in Java if statements do not by themselves create a new scope (until Java 14, that is!). However, braced statement blocks (i.e. {…}) do create a new, nested scope.

However, this is unrelated with your issue, because nested scopes can access variables from their parent scope (otherwise most code wouldn’t work). So the following works:

int x = 1;

{
    System.out.println(x);
}

If {…} didn’t inherit the parent scope, that code wouldn’t work.

As noted by Ivar in the comments, your code works because you did initialise the max variable to 0 outside the loop.


That said, the code can be made simpler and more logical. In particular, the calculation of the average and the output should not be part of the loop but instead happen afterwards:

Scanner inp = new Scanner(System.in);
int sum = 0;
int count = 0;
int max = 0;
int num;

do {
    sum  = num;
    num = inp.nextInt();
    if (num > max) {
        max = num;
    }
      count;
} while (num >= 0);

double average = sum / (double) (count - 1);
System.out.printf("%d %.2f\n", max, average);

A commonly used alternative way of writing this loop is using for(;;) with break;. This variant has the alternative that we can limit the scope to num to the loop: it is generally desirable to make variable scope as small as possible, and to initialise a variable at the site of its declaration.

…
for (;;) {
    int num = inp.nextInt();
    if (num < 0) break;

    sum  = num;
    if (num > max) {
        max = num;
    }
      count;
}
…
  • Related