Why isn't my age variable in the while loop destroyed...need help understanding scope

0 Number Double07 · May 29, 2015
That is my code and I know it works. It is designed for the user to input an age, and if the age is not 1, 2, or 3, it will continue to ask the user to input an age until the user inputs an age within that range. I'm just a little lost because I thought that since the while loop has its own block, it would have it's own scope and therefore the age variable would be destroyed after it ran. Maybe I'm over-thinking things, but I would appreciate an explanation.

import java.util.Scanner;

class Age{
    public static void main(String args[]){
    int age;
    Scanner agein = new Scanner (System.in);
    System.out.println("Enter an age");
    age = agein.nextInt();
    
    while (age >3 || age

Post a Reply

Replies

Oldest  Newest  Rating
0 Number Double07 · May 29, 2015
I also need help pasting code, lol.  it looks like this...

import java.util.Scanner;

class Age{
    public static void main(String args[]){
    int age;
    Scanner agein = new Scanner (System.in);
    System.out.println("Enter an age");
    age = agein.nextInt();
    
    while (age >3 || age <1){
        System.out.println("Enter age of 1, 2, or 3");
        age = agein.nextInt();
        }
    
    switch(age){
        case 1:
        System.out.println("The age is " + age);
        break;
        
        case 2:
        System.out.println("The age is " + age);
        break;
        
        case 3:
        System.out.println("The age is " + age);
        break;
        
        }
        }
        }
       
0 Robert Herges · May 30, 2015
I am a bit confused by your question. Are you wondering why the age variable isn't destroyed after the while loop? If so, the age variable is declared in the function main, even if you declared the age variable in the while loop, it would still be usable anywhere in the function main.

On an unrelated note, the switch statement in your code serves no purpose. This code would accomplish the same thing that your switch statement does.

System.out.println("The age is" + age);
0 Number Double07 · May 30, 2015
Thanks Robert!  I was getting confused by the curly braces and scopes.  It's for functions where it goes out of scope and is destroyed.  For instance....

int regal( ){
int apple;
}
....apple destroyed here.

hehe, and thanks for the unrelated advice.  I wanted to get practice with switch statements because I rarely use it, so that's why I put it in.  But yea, it really serves little purpose other than to make my code longer. 
  • 1

Java / Android Development

106,989 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator