-2

I get the thought process and meaning of static, but why?

    import java.io.*;
    import java.util.Scanner;
    class AgeException extends Exception
    {
        public AgeException()
        {
        super("That age isn't valid.");
        }
    }
    class ExceptionsInputs {
    Scanner sc = new Scanner(System.in);
    public static void main(String arg[])
    {
        try
        {
            int age = sc.nextInt();
                    if (age >= 0) {
                    }
                    if (age <= 125)
                    {
                    }
        }
        catch(AgeException ae)
        {
        System.out.println("Your Exception");
        }
    }
    }

The error I'm getting lies in line 16, int age = sc.nextInt();. A non static variable (sc) is being referenced/called as static. But why, exactly?

I think I know that the scanner variable I am using is dynamic only because it's reusable, right?

If that's true, what bit of code would I even use for this situation?

Aren't int data types are always static? Would something with nextInt work?

tod
  • 1,539
  • 4
  • 17
  • 43
Dont
  • 35
  • 7

1 Answers1

1

The compiler message says exactly what it is supposed to say when it encounters such error. (Instance members can't be accessed without using a reference to the instance, either explicit or implicit this reference)
And it is unrelated to Scanner class.

Display Name
  • 8,022
  • 3
  • 31
  • 66