Search code examples
javatry-finally

Why does a variable need to be static in the finally-block


I use Eclipse for programming and it tells me if want to output the "Input String"

Cannot make a static reference to the non-static field Input

Why has the variable to be static in the finally-block?

import java.util.Scanner;

public class NameSort {
    String Input;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            System.out.println("Inupt some Text");
            while (sc.hasNextLine()){

                String Input = sc.nextLine();
                System.out.println(Input);
                if (Input.toLowerCase().equals("ende")) {
                    System.exit(0);
                    sc.close();
                }
            }

        } finally {
            if (sc != null)
            sc.close();
            System.out.print(Input);
        }
    }
}

Solution

  • In Java, you can not use/call a non-static variable/method from a static method. Also, other than the following code, the rest of your code is useless:

    import java.util.Scanner;
    
    public class NameSort {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String input;
            System.out.println("Inupt some Text");
            while (!(input = sc.nextLine()).equals("ende")) {
                System.out.println(input);
            }
        }
    }
    

    A sample run:

    Inupt some Text
    hello
    hello
    hi
    hi
    ende